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); }
source share