向 DefaultModelBinder MVC2 添加多个前缀
我已经查看了大多数 ModelBinding 示例,但似乎无法收集我正在寻找的内容。
我想:
<%= Html.TextBox("User.FirstName") %>
<%= Html.TextBox("User.LastName") %>
帖子上绑定到此方法
public ActionResult Index(UserInputModel input) {}
在UserInputModel 为的
public class UserInputModel {
public string FirstName {get; set;}
public string LastName {get; set;}
}
约定是使用不带“InputModel”的类名,但我不想每次都使用 BindAttribute 指定它,即:
public ActionResult Index([Bind(Prefix="User")]UserInputModel input) {}
我已经尝试覆盖 DefaultModelBinder 但似乎无法找到注入这一点功能的正确位置。
I've looked at most of the ModelBinding examples but can't seem to glean what I'm looking for.
I'd like:
<%= Html.TextBox("User.FirstName") %>
<%= Html.TextBox("User.LastName") %>
to bind to this method on post
public ActionResult Index(UserInputModel input) {}
where UserInputModel is
public class UserInputModel {
public string FirstName {get; set;}
public string LastName {get; set;}
}
The convention is to use the class name sans "InputModel", but I'd like to not have to specify this each time with the BindAttribute, ie:
public ActionResult Index([Bind(Prefix="User")]UserInputModel input) {}
I've tried overriding the DefaultModelBinder but can't seem to find the proper place to inject this tiny bit of functionality.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传递给
BindModel
函数的ModelBindingContext
对象中的ModelName
属性就是您要设置的内容。这是一个执行此操作的模型绑定程序:在您的
Application_Start
中注册它,如下所示:现在您将不再需要为您指定使用此模型绑定程序的类型添加
Bind
属性!The
ModelName
property in theModelBindingContext
object passed to theBindModel
function is what you want to set. Here's a model binder that does this:Register it in your
Application_Start
like so:Now you will no longer to need to add the
Bind
attribute for types you specify use this model binder!BindAttribute 可以在类级别使用,以避免为 UserInputModel 参数的每个实例重复它。
======编辑======
只需从表单中删除前缀或在视图模型上使用 BindAttribute 将是最简单的选择,但另一种选择是为 UserInputModel 类型注册自定义模型绑定器,并显式查找您想要的前缀。
The BindAttribute can be used at the class level to avoid duplicating it for each instance of the UserInputModel parameter.
======EDIT======
Just dropping the prefix from your form or using the BindAttribute on the view model would be the easiest option, but an alternative would be to register a custom model binder for the UserInputModel type and explicitly looking for the prefix you want.