模型绑定到具有相同属性名称的多个类型
我有一个包含 2 个列表框的视图:受众和受众。 我正在
尝试向我的控制器提交一个包含所选索引的表单,该控制器具有此签名的操作方法
public JsonResult Submit(Audience aud, Locale loc)
{
// do stuff
}
: Locale 有一个 ID 属性,因此 Model Binder 对于将所选值分配给哪个属性有点困惑。当受众应该有“2”而区域设置应该有“1”时,两者都被分配值“1”。
问题是如何让页面在提交时区分两者?我们尝试在 Locale 的 ID 值前面添加“locale.”,因此作为数据传递到控制器的参数字符串如下所示 "&locale.id=1&audience.id=2"
但这似乎不起作用。
有什么建议吗?如果需要更多信息,我会提供。
谢谢
戴夫
I have a view that contains 2 list boxes: Audience & Locale
I'm trying to submit a form that contains the selected index of both to my controller, which has an action method of this signature:
public JsonResult Submit(Audience aud, Locale loc)
{
// do stuff
}
The problem I'm having is both Audience & Locale have an ID property, so the Model Binder is a little bit confused over which to assign the selected values to. Both get assigned the value '1', when Audience should have '2' and Locale should have '1'
The question is how can I get the page to differentiate between the two when it's submitting? We've tried prepending the ID value for Locale with "locale.", so the parameter string that gets passed as data to the Controller looks like"&locale.id=1&audience.id=2"
but that doesn't seem to work.
Any suggestions? If more info is needed, I'll supply it.
Thanks
Dave
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
每个 Audience 字段在 html 字段中的名称中应该有“audience”前缀:audience.id,audience.name,...
Use:
Every Audience field should have "audience" prefix in name in html field: audience.id,audience.name,...
您应该有一个特定的 ViewModel 来将数据放入您的提交操作中。该对象应该具有 AudienceId 和 LocaleId。创建下拉菜单时,您应该使用与您期望的名称相匹配的名称来创建它们。
You should have a specific ViewModel for taking data into your Submit Action. That object should have AudienceId and LocaleId. When you create your dropdowns you should create them with names that match what you expect.