ASP.NET MVC 2 Create Model using POST
I have the following model:
public class Product {
public int Id { get; set; }
public string Name { get; set; }
private int CategoryId { get; set; }
public Category Category { get; set; }
public string InventoryDetails { get; set; }
}
I have an action in my controller which is used to create a new product. My question is how to limit the properties of my model which can be bound from the POST data? Because I want only the Name and CategoryId to be bound by the user POST data. Or is it better to create a separate viewmodel which has only the开发者_开发知识库se properties that can be bound?
public ActionResult Create(Product p)
or
public ActionResult Create(CreateProductViewModel model)
where
public class CreateProductViewModel {
public string Name {get; set;}
public int CategoryId {get;set;}
}
Go with the view model. This will decouple your view from the data model. As you've discovered they don't always have the same needs and the model should be specific to the view. You can map properties manually or use AutoMapper for more complex scenarios.
Always go with a ViewModel. Using a ViewModel, it is much more easier to bend your Data Model according to the needs of the view. Here is a cool article by Jimmy Bogard.
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
Or you can do something like this:
public ActionResult Create (FormCollection collection) {
Product p = new Product();
UpdateModel(p, new string[] { "Name", "CategoryId" });
//....
}
public ActionResult Create([Bind(Exclude = "Category,Id,InventoryDetails")]Product prod){
/*do your magic*/
}
ASP.NET MVC default model binder will exclude unnecessary fields.
note: If your view data format is nearly equal to data model creating separate view model is not a good practice.create seperate view model only if two are different.
精彩评论