Html.BeginForm calls wrong url with action / 1

In my application, I have a form at "/ Project / AddFund / 1":

@using (Html.BeginForm("AddFund", "Project", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div>
       ...
       <input type="submit" value="Save" class="btn btn-default" />
    </div>
}

      

But the html rendering is -

<form method="post" action="/Project/AddFund/1" novalidate="novalidate"><input type="hidden" value="tM8Gdmnki5mdHiTeuc9m_Ga_LY0hPhuSyAiXs6Ae9yedUn9h-sS-ihBC5Iy3NZtrxBmA7TRbV_jEPgvztuHT3Y6seGZvaLWJUemwg2_5OBR23dVELfJ1wHb0pvAcAOuu0huy_PzAozsQtxZUSBFUQw2" name="__RequestVerificationToken">    <div>
...
</form>

      

In my controllers, this method is supposed to catch the form view, but it really doesn't work because of the url with / id, the controller code is never called:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddFund(AddFundToProjectViewModel model)
{...}

      

This is an exception:

No parameterless constructor defined for this object. [MissingMethodException: No parameterless constructor defined for this object.] exception is thrown

      

As StephenMuecke said in a comment, I was using a ModelView with one custom constructor, but not the default constructor ... That was a bug!

How do I get this form to work with this controller?

Thank you in advance

+3


source to share


1 answer


When you make a request to an action with parameters, MVC tries to create those parameters for you and populate them with data coming from the request body, route values, query string ... (this is the value of the providers).

This process is called model binding. And if there is a parameter that is an object, for example AddFundToProjectViewModel model

, the first step to bind to a model is to create an empty instance of that object for which it needs a default constructor (no parameters).



After the object is created, it tries to set the property values ​​coming from the value providers with the appropriate names.

By default, all classes have a default constructor (no parameters). But, if you define a constructor with parameters, then no default constructor is provided. So, to solve your problem, add a parameterless constructor to your class AddFundToProjectViewModel

so that the model binding can do its job.

-1


source







All Articles