Home > Mobile >  How does Controller get the Model from the View FormMethod.Post?
How does Controller get the Model from the View FormMethod.Post?

Time:01-04

In my ASP.NET MVC 5.2 application running .NET Framework v4.5.2, my AdminController has an InventoryQueryList method that accepts the model:

[HandleError]
[HttpPost]
public ActionResult InventoryQueryList(CheckInventoryQueryModel model)
{
    // ...
}

My view contains the model and calls the InventoryQueryList method on POST:

@model CCNRebuild.Models.CheckInventoryQueryModel
@{
    ViewBag.Title = "InventoryQuery";
    Layout = "~/Views/Shared/_ConsoleLayout.cshtml";
}

@using (Html.BeginForm("InventoryQueryList", "Admin", FormMethod.Post))
{
    @Html.AntiForgeryToken();
    <label>
        Dealer:@Html.DropDownListFor(m => m.DealerID, Model.Dealerships)
    </label>
    ...
    <input type="submit" value="Submit" />
}

But, whenever I click the submit button, I get an error:

MissingMethodException: No parameterless constructor defined for this object.

screenshot

Why is the view not passing my model parameter to the controller?

The controller has never had a parameterless constructor in the 3 months that I have been working here.

NOTE: I tried to only show relevant code, and I left out anything unnecessary. If there is anything missing that needs to be seen, please comment and I'll try to oblige.

CodePudding user response:

The error is telling you that CheckInventoryQueryModel doesn't have a parameterless constructor, and it needs one. So you would either:

  1. Remove whatever non-parameterless constructor(s) it does have (and update related code accordingly), or
  2. Add a parameterless constructor.

The model binder needs a parameterless constructor in order to construct an instance of the model. (Unless you write a custom model binder for this type. Which probably isn't the road you want to take, but is an option.) This is a fairly common pattern in frameworks that automate model instance creation. Entity Framework, for example.


As for the actual questions being asked...

How does Controller get the Model from the View FormMethod.Post?

and

Why is the view not passing my model parameter to the controller?

It just sounds like you were misinterpreting the error. I see no reason to suggest that the page isn't passing the form value(s) to the server. Though you can always confirm this in your browser's debugging tools by observing the HTTP request being made when posting the form.

The request sends the data to the server, and can do so in a variety of ways. Form posts are generally key/value pairs. The ASP.NET MVC framework's model binder uses those key/value pairs to populate properties on the model. It just couldn't do that in this case because it couldn't create an instance of the model to be populated.

  • Related