Different Models for Get and Post - MVC

As I understand from the question below, it should be possible to use different models for the Get and Post actions. But for some reason I canโ€™t achieve this.

What am I missing?

Related question: Using two different models in a controller action for POST and GET

Model

public class GetModel { public string FullName; public string Name; public int Id; } public class PostModel { public string Name; public int Id; } 

controller

 public class HomeController : Controller { public ActionResult Edit() { return View(new GetModel {Id = 12, Name = "Olson", FullName = "Peggy Olson"}); } [HttpPost] public ActionResult Edit(PostModel postModel) { if(postModel.Name == null) throw new Exception("PostModel was not filled correct"); return View(); } } 

View

 @model MvcApplication1.Models.GetModel @using (Html.BeginForm()) { @Html.EditorFor(x => x.Id) @Html.EditorFor(x=>x.Name) <input type="submit" value="Save" /> } 
+8
asp.net-mvc asp.net-mvc-3 model-binding
source share
2 answers

Your models do not use proper accessors, so binding to the model does not work. Change them to this and it should work:

 public class GetModel { public string FullName { get; set; } public string Name { get; set; } public int Id { get; set; } } public class PostModel { public string Name { get; set; } public int Id { get; set; } } 
+9
source share

A little clarification

GET and POST controller actions can easily use whatever types they need. We are not really talking about models here. A model is a collection of classes / types that represent the state / data of an application. Therefore, an application or data model.

What do we mean:

  • view model types
  • action method parameter types

So, your application model remains the same. Both GetModel and PostModel are just two classes / types in this model. They are not a model in their own way.

Various types? Of course we can!

In your case, you use the GetModel view model type, and then pass your data to the PostModel action parameter. Since these two classes / types have properties with the same matching names, the PostModel will be able to populate the PostModel properties by PostModel . If the property names are not the same, you will need to change the view to rename the inputs to display the property names of the POST action type.

You can also have a view with type GetModel , and then send an action with several different types of diagrams, for example:

 public ActionResult Edit(Person person, IList<Address> addresses) { ... } 

Or something else. You just need to make sure that these messages can be associated with these parameters and their properties like ...

+6
source share

All Articles