I have the following code:
[HttpGet]
public ActionResult Edit(int req)
{
var viewModel = new EditViewModel();
viewModel.RequestId = int;
return View(viewModel);
}
[HttpPost]
Public ActionResult Edit(EditViewModel viewModel)
{
// some code here...
}
It works fine: when the edit form is posted, I have the action controller who is called.
Now I modify some little bit my code like this:
[HttpGet]
public ActionResult Edit(int req)
{
var viewModel = new EditViewModel(req);
return View(viewModel);
}
[HttpPost]
Public ActionResult Edit(EditViewModel viewModel)
{
// some code here...
}
public class EditViewModel()
{
public EditViewModel(int req)
{
requestId = req;
}
...
}
In this new version, I have a view model with a contructor.
This time, when my form is posted back, the action controller is never triggered.
Any idea?
Thanks.
That’s normal. The default model binder can no longer instantiate your view model as it doesn’t have a parameterless constructor. You will have to write a custom model binder if you want to use view models that don’t have a default constructor.
Normally you don’t need such custom constructor. You could simply have your view model like that:
and the POST action like that:
and now all you have to do is POST the
requestIdparameter instead ofreqand the default model binder will do the job.And if for some reason you wanted to use a view model with custom constructor, here’s an example of how the custom model binder might look like:
which will be registered in your
Application_Start: