Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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;}
}
like image 620
Boyan Mihaylovv Avatar asked Jul 10 '26 19:07

Boyan Mihaylovv


1 Answers

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.

like image 145
tvanfosson Avatar answered Jul 14 '26 17:07

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!