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;}
}
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.