Data wiring when my view model has a constructor does not work

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 great: when you edit the form, I have a calling action controller.

Now I am slightly modifying my code as follows:

 [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 constructor.

This time, when my form is submitted back, the action controller never starts.

Any idea?

Thanks.

+8
asp.net-mvc
source share
1 answer

This is normal. By default, the middleware can no longer instantiate your view model because it does not have a constructor without parameters. You will need to write a custom mediator if you want to use view models that do not have a default constructor.

Usually you do not need such a custom constructor. You can simply create a model of your kind:

 public class EditViewModel() { public int RequestId { get; set; } } 

and the POST action:

 [HttpPost] public ActionResult Edit(EditViewModel viewModel) { // some code here... } 

and now all you have to do is POST instead of requestId instead of req , and the binder will do the job by default.

And if for some reason you wanted to use a view model with a custom constructor, here is an example of what a custom mediator looks like:

 public class EditViewModelBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var req = bindingContext.ValueProvider.GetValue("req"); if (req == null) { throw new Exception("missing req parameter"); } int reqValue; if (!int.TryParse(req.AttemptedValue, out reqValue)) { throw new Exception(string.Format("The req parameter contains an invalid value: {0}", req.AttemptedValue)); } return new EditViewModel(reqValue); } } 

which will be registered in your Application_Start :

 ModelBinders.Binders.Add(typeof(EditViewModel), new EditViewModelBinder()); 
+12
source share

All Articles