【问题标题】:ValidationMessage not showing up when using more than one model使用多个模型时不显示 ValidationMessage
【发布时间】:2014-01-23 12:42:36
【问题描述】:

我有使用 2 个模型的表单,所以我以这种方式包含它:

@model Equipment.Models.PublicViewModel

PublicViewModel 在哪里

namespace Equipment.Models
{
    public class PublicViewModel
    {
        public Device Devices { get; set; }
        public UserCredentials Data { get; set; }
    }
}

例如 UserCredential 类如下所示:

namespace Equipment.Models
{
    public class UserCredentials
    {
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
}

还有我的表格:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <hr />
        @Html.ValidationSummary(true)

        <div class="input-group">
            @Html.LabelFor(model => model.Data.UserName, new { @class = " input-group-addon" })
            @Html.TextBoxFor(model => model.Data.UserName, new { @class = "form-control" })<br />
            @Html.ValidationMessageFor(model => model.Data.UserName)
        </div>

        ...

        <div class="input-group">
            @Html.LabelFor(model => model.Devices.DeviceSerialNumber, new { @class = " input-group-addon" })
            @Html.TextBoxFor(model => model.Devices.DeviceSerialNumber, new { @class = "form-control" })<br />
            @Html.ValidationMessageFor(model => model.Devices.DeviceSerialNumber)
        </div>
        ...
}

在其他形式中,当我只使用一个模型时,一切正常。 谁能告诉我为什么这不适用于 2 个模型?

【问题讨论】:

    标签: c# .net asp.net-mvc validationmessage


    【解决方案1】:

    从此LINK 确认您不能对嵌套对象进行客户端验证。只有属性级别的验证器可以发出客户端验证。

    因此,如@Darin 在this 链接上所述,您可以使用FluentValidation.NET,而不是使用DataAnnotations

    您可以选择的另一种方法是为两个模型设置单独的局部视图,并从单个视图调用这些视图并根据需要将模型传递给这些视图。

    像这样

    <div class="input-group">
            @Html.Partial("ViewForModelData", Model.Data)
            </div>
    
    
            <div class="input-group">
             @Html.Partial("ViewForModelDevice", Model.Device)
            </div>
    

    那么您可以在这两个视图中拥有单独的验证摘要!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-02
      • 2018-09-29
      • 2015-10-27
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多