Click here to Skip to main content
14,695,617 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone

I'm building an MVC3 application. I have my data models defined, and now I have to create ViewModels for specific actions.

I'm using automapper. Here's an example situation:

public class modelname{
  public int id {get;set;}
  public string name {get;set;}
  public string otherfield {get;set;}
  //many other properties

public class modelnameEditViewModel{
  public int id {get;set;}
  public string name {get;set;}

protected void Application_Start(){
   AutoMapper.Mapper.CreateMap<Models.Job, Models.JobEditViewModel>();
   AutoMapper.Mapper.CreateMap<Models.JobEditViewModel, Models.Job>();


//get the model from db, returns a strongly-typed partialview for viewmodel;

public ActionResult Edit(int id)
  modelname model = db.modelname.find(id);
  modelnameEditViewModel viewmodel = Automapper.Mapper.Map<modelname, modelnameEditViewModel>(model);

 return PartialView("PartialEdit", viewmodel);

Is it correct to do the following to update the model with only the properties of ViewModel?
What is the "best practice" for where to place my ViewModels? can I keep them in the same file along with the Model?

Thanks in advance,

Additional Tags are added.
Updated 12-Dec-11 14:19pm

A ViewModel class is there to encapsulate multiple pieces of data represented by instances of classes into one easy to manage object that you can pass to your View.

There are no good place to keep your models in. You can keep them in separate assembly if the project is big and there are a lot of ViewModels (Data Transfer Objects). Also you can keep them in separate folder of the site project.
I don't know why, my post has been edited and the most important part of the question is missing..

The question about updating the main model via a ViewModel that has "some" of the properties of the main model.. is it correct to do it this way?

//http post from a strongly-typed partial view for ViewModel
public ActionResult Edit(modelnameViewModel viewmodel)
   //get the original model from db
   modelname model = db.modelname.find(id);

   Automapper.Mapper.Map<modelnameeditviewmodel,>(viewmodel, model);//"maps" the values of the properties of the posted viewmodel into the "main" model


 return PartialView("FullDetails", model);

This actually works, but I'm not shure about it being "formally correct" or not

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900