MVC 直接在单个对象上调用模型绑定器
有没有一种方法可以为单个对象调用模型绑定器?
我不想要/不需要自定义模型绑定器 - 我只想做这样的事情:
MyViewModel1 vModel1 = new MyViewModel1();
InvokeModelBinder(vModel1);
MyViewModel2 vModel2= new MyViewModel2();
InvokeModelBinder(vModel2);
当我完成后,vModel1 和 vModel2 的属性都已绑定到传入请求中的内容。由于我们的控制器/操作的编写方式,我不一定希望在操作方法的输入列表中列出 vModel1 和 vModel2 (因为最终可能会出现一个可能很长的视图模型列表,可供选择绑定)。
Is there a way that I can invoke the model binder for a single object?
I don't want/need a custom model binder - I just want to do something like this:
MyViewModel1 vModel1 = new MyViewModel1();
InvokeModelBinder(vModel1);
MyViewModel2 vModel2= new MyViewModel2();
InvokeModelBinder(vModel2);
And when I'm done, the properties of both vModel1 and vModel2 have been bound to what's in the incoming request. Because of the way that our controller/action is being written, I don't necessarily want to list vModel1 and vModel2 in the action method's input list (since there will end up being a potentially long list of view models to optionally bind against).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Controller.UpdateModel :
更新
请注意,如果控制器中的
ModelState
存在验证错误(与在操作中传递的模型相关),则UpdateModel(对于任何模型)都会抛出异常,尽管UpdateModel成功并且vModel1 是已更新。因此,应该删除 ModelState 中的错误,或者将 UpdateModel 放入 try/catch 中并忽略异常Use Controller.UpdateModel:
Update
Note if
ModelState
in controller has validation errors (related to model passed in action), UpdateModel (with any model) throws excetion, despite UpdateModel success and vModel1 is updated. Therefore errors in ModelState should be removed, or put UpdateModel in try/catch and just ignore excetion恕我直言,这在很多层面上都是错误的:
模型绑定由反射驱动。在调用操作之前,它将反映方法参数列表,并且对于每个对象及其属性,它将调用模型绑定器以从各种值提供程序(表单 POST 值提供程序、url 参数等)中查找每个属性的值。在模型绑定期间,也会完成 ModelState 验证。
因此,如果不使用默认的 ASP.NET MVC 来执行此操作,您将失去所有这些。
即使您要像这样手动获取模型绑定器:
您可以看到需要初始化 ModelBindingContext,ASP.NET MVC 将根据它所反映的当前属性在内部执行此操作。以下是 ASP.NET MVC 源代码的片段:
}
This is wrong on many levels IMHO:
Model binding is driven by reflection. Before an action is invoked it will reflect the method parameters list and for each object and its properties it will invoke a model binder to find a value for each property from the various value providers (form POST values provider, url parameters, etc). During model binding the ModelState validation is done as well.
So by not using the default ASP.NET MVC to do this you are losing all that.
Even if you were to manually get hold of a model binder like that:
You can see that you need to initalize a ModelBindingContext, something that ASP.NET MVC will do internally based on the current property it is reflecting. Here is the snipped from the ASP.NET MVC source code:
}