ASP.NET MVC message model example?

I watched the HaHaa presentation on ASP.NET MVC from MIX , and they mentioned the use of the Post model, where I think they told you they could use a model that was ONLY for publication. I tried to find examples for this. Don't I understand what they say? Does anyone have an example of how this can work in a strongly typed presentation where the presentation model and publication model are not of the same type?

+4
source share
2 answers

The following is an example of ScottGu. As @SLaks explained, when the POST is received, MVC will try to create a new MyPostName object and map its properties to from fields. It will also update the ModelState property with matching and validation results.

When an action returns a view, it should also provide it with a model. However, the view should not use the same model. In fact, the view can be strongly typed with another model that contains extended data, for example, it can have navigation properties associated with foreign keys in the database table; in this case, the logic for matching the POST model with the view model will be contained in the POST action.

public class MyGetModel { string FullName; List<MyGetModel> SuggestedFriends; } public class MyPostModel { string FirstName; string LastName; } //GET: /Customer/Create public ActionResult Create() { MyGetModel myName = new MyGetModel(); myName.FullName = "John Doe"; // Or fetch it from the DB myName.SuggestedFriends = new List<MyGetModel>; // For example - from people select name where name != myName.FullName Model = myName; return View(); } //POST: /Customer/Create [HttpPost] public ActionResult Create(MyPostModel newName) { MyGetModel name = new MyGetModel(); name.FullName = newName.FirstName + "" + newName.LastName; // Or validate and update the DB return View("Create", name); } 
+8
source

The POST model will only be used to pass data to your action method.

The model that the POST action sends to its presentation does not have to be associated with the model it received (and usually will not).
Similarly, a model in which the initial GET action (which shows the form in the first place) goes to its presentation (which obeys the POST action), does not have to be associated with the model that the POST action takes (although it will usually be the same model)

As long as it has properties that match your input parameters, you can use whatever model you want for the parameter for the POST action.

+2
source

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


All Articles