ASP.NET MVC 2 Create a 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 that is used to create a new product. My question is how to limit the properties of my model that may be associated with POST data? Because I want only the name and CategoryId to be connected by POST user data. Or is it better to create a separate view model that can only link these properties?

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;}
}
+3
source share
4 answers

. . , , . AutoMapper .

+7

- :

public ActionResult Create (FormCollection collection) {
    Product p = new Product();
    UpdateModel(p, new string[] { "Name", "CategoryId" });
    //....
}
0
public ActionResult Create([Bind(Exclude = "Category,Id,InventoryDetails")]Product prod){

/*do your magic*/

}

ASP.NET MVC .

Note. If your view data format is almost equal to the data model, creating a separate view model is not good practice. Create a separate view model only if there are two different objects.

0
source

Source: https://habr.com/ru/post/1757842/


All Articles