我有一个ViewModel类来封装个人"和业务"模型.我的问题是,两个模型都有一个名为"Email"的属性,并且模型绑定无法区分两者.
I have a ViewModel class to encapsulate "Personal" and "Business" models. My problem is that both models have a property called "Email" and the model binding is not able to make a distinction between the two.
我读到[Bind(Prefix = ...用于解决此问题,但我无法看到有关如何实现此目的的简洁示例.
I read that [Bind(Prefix = ... is used to resolved this issue, but I have not been able to see a concise example on how to achieve this.
public class BusinessFormViewModel { public Business Business { get; set; } public ContactPerson ContactPerson { get; set; } public BusinessFromView(Business business, ContactPerson contactPerson) { Business = business; ContactPerson = contactPerson; } }如何使用绑定前缀来解决此问题?
How do I use the Bind Prefix to fix this?
推荐答案我相信,如果发布的表单元素的名称中包含前缀,则绑定将正确完成.这就是模板化助手(即EditorFor)呈现控件的方式,并且我的嵌套viewmodel被正确绑定.例如,在您的情况下,您的视图将具有如下所示的表单元素:
I believe that if the form elements that are posted have prefixes included in the name, the binding will be done properly. This is how the templated helpers (i.e. EditorFor) renders the controls, and my nested viewmodels are bound properly. For example, in your case, your view would have form elements something like this:
... <input type="text" name="Business.Email" value="<%=this.Model.Business.Email %>" /> ... <input type="text" name="ContactPerson.Email" value="<%=this.Model.ContactPerson.Email %>" /> ...或者,使用模板化助手(在mvc 2中):
Or, using templated helpers (in mvc 2):
... <%= Html.TextBoxFor(m => m.Business.Email) %> ... <%= Html.TextBoxFor(m => m.ContactPerson.Email) %> ...您的控制器只需将BusinessFormViewModel作为参数即可,
And your controller would simply take a BusinessFormViewModel as a parameter, as so:
public BusinessFromView(BusinessFormViewModel businessForm) { Business = businessForm.Business; ContactPerson = businessForm.ContactPerson; }更多推荐
两个名称相同的字段
发布评论