views:

49

answers:

4

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 these 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;}
}
+7  A: 

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.

tvanfosson
A: 

Or you can do something like this:

public ActionResult Create (FormCollection collection) {
    Product p = new Product();
    UpdateModel(p, new string[] { "Name", "CategoryId" });
    //....
}
Johannes Setiabudi
But due to the use of "magic" strings you've lost refactorability and type safety.
Ryan
Not really, you can always enumerate them if you want or save them in constant variables. I am just providing options.
Johannes Setiabudi
+1  A: 

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

Praveen
A: 
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.

DSharper