ASP.NET MVC - 表单中的多个模型和模型绑定器
我有一个表格需要填充 2 个模型。 通常我在表单后操作上使用 ModelBinderAttribute,即
[Authorize]
[AcceptVerbs("POST")]
public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
{
///Do stuff
}
在我的表单中,字段的命名与模型属性相同...
但是在这种情况下,我有 2 个不同的模型需要填充。
我该怎么做呢? 有任何想法吗? 是否可以?
I have a form which needs to populate 2 models. Normally I use a ModelBinderAttribute on the forms post action i.e.
[Authorize]
[AcceptVerbs("POST")]
public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
{
///Do stuff
}
In my form, the fields are named the same as the models properties...
However in this case I have 2 different models that need populating.
How do I do this? Any ideas? Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上...最好的方法是这样做:
}
您可以使用多个属性!
Actually... the best way is to do this:
}
You CAN use multiple attributes!
在这种情况下,我倾向于创建一个模型类型来包装所涉及的各种模型:
...并绑定那个。
In cases like this, I tend to make a single model type to wrap up the various models involved:
...and bind that.
UpdateModel 或 TryUpdateModel 方法可用于执行此操作。 您可以传递模型、要绑定的模型、要绑定到该模型的项目的前缀以及表单。 例如,如果您的 Item 模型具有“Item.Value”的表单变量,那么您的更新模型方法将是:
如果您使用实体框架,值得指出的是 UpdateModel 方法并不总是在某些条件下工作。 不过,它确实与 POCO 配合得特别好。
The UpdateModel or TryUpdateModel method can be used to do this. You can pass through the model, the model you wish to bind, the prefix of the items you wish to bind to that model and the form. For example if your Item model has form variables of "Item.Value" then your update model method would be:
If you're using the entity framework, it's worth pointing out that the UpdateModel method doesn't always work under some conditions. It does work particularly well with POCOs though.