当我的视图模型具有构造函数时发布数据不起作用 [英] Posting data when my view model has a constructor does not work
问题描述
我有以下代码:
[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.
有什么想法吗?
谢谢.
推荐答案
这很正常.默认模型绑定器无法再实例化您的视图模型,因为它没有无参数构造函数.如果要使用没有默认构造函数的视图模型,则必须编写自定义模型绑定器.
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; }
}
和这样的 POST 操作:
and the POST action like that:
[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
// some code here...
}
现在您所要做的就是发布 requestId
参数而不是 req
并且默认模型绑定器将完成这项工作.
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);
}
}
将在您的 Application_Start
中注册:
ModelBinders.Binders.Add(typeof(EditViewModel), new EditViewModelBinder());
这篇关于当我的视图模型具有构造函数时发布数据不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!