Click here to Skip to main content
15,895,777 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:
C#
//Models

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

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


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

//Controller

//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,
Alberto

[EDITED]
Additional Tags are added.
Posted
Updated 12-Dec-11 13:19pm
v3

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.
 
Share this answer
 
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?

C#
//http post from a strongly-typed partial view for ViewModel
[HttpPost]
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

 UpdateModel(model);
 db.SaveChanges();

 return PartialView("FullDetails", model);
 
}


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

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