两个同名字段

发布于 2024-08-29 12:11:10 字数 512 浏览 3 评论 0原文

我有一个 ViewModel 类来封装“个人”和“业务”模型。我的问题是,两个模型都有一个名为“电子邮件”的属性,并且模型绑定无法区分两者。

我读到 [Bind(Prefix = ...) 用于解决此问题,但我还没有看到有关如何实现此目的的简明示例。

public class BusinessFormViewModel
{
    public Business Business { get; set; }
    public ContactPerson ContactPerson { get; set; }

    public BusinessFromView(Business business, ContactPerson contactPerson)
    {
        Business = business;
        ContactPerson = contactPerson;
    }
}

如何使用 Bind Prefix 来解决 此问题解决这个问题吗?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开半夏魅人心 2024-09-05 12:11:10

我相信,如果发布的表单元素的名称中包含前缀,则绑定将正确完成。这就是模板化助手(即 EditorFor)呈现控件的方式,并且我的嵌套视图模型已正确绑定。例如,在您的情况下,您的视图将具有如下所示的表单元素:

...
<input type="text" name="Business.Email" value="<%=this.Model.Business.Email %>" />
...
<input type="text" name="ContactPerson.Email" value="<%=this.Model.ContactPerson.Email %>" />
...

或者,使用模板化助手(在 mvc 2 中):

...
<%= Html.TextBoxFor(m => m.Business.Email) %>
...
<%= Html.TextBoxFor(m => m.ContactPerson.Email) %>
...

并且您的控制器将简单地将 BusinessFormViewModel 作为参数,如下所示:

public BusinessFromView(BusinessFormViewModel businessForm)
{
    Business = businessForm.Business;
    ContactPerson = businessForm.ContactPerson;
}

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 %>" />
...

Or, using templated helpers (in mvc 2):

...
<%= Html.TextBoxFor(m => m.Business.Email) %>
...
<%= Html.TextBoxFor(m => m.ContactPerson.Email) %>
...

And your controller would simply take a BusinessFormViewModel as a parameter, as so:

public BusinessFromView(BusinessFormViewModel businessForm)
{
    Business = businessForm.Business;
    ContactPerson = businessForm.ContactPerson;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文