发布数据时,我认为模式有一个构造函数不工作 [英] Posting data when my view model has a constructor does not work
问题描述
我有以下的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.
现在我修改一些点点我的code是这样的:
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...
}
现在你需要做的就是POST的的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屋!