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:
public class EditViewModel()
{
public int RequestId { get; set; }
}
and the POST action like that:
[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
// some code here...
}
and now all you have to do is POST the requestId
parameter instead of req
and 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:
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());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…