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) {
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());
Darin Dimitrov
source share