使用多个模型时,ValidationMessage未显示

时间:2014-01-23 12:42:37

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

我有使用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个型号?

1 个答案:

答案 0 :(得分:1)

从此LINK确认您无法对嵌套对象进行客户端验证。只有属性级验证器才能发出客户端验证。

所以使用DataAnnotations,你可以使用FluentValidation.NET {@ 3}} {@ 3}链接

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

喜欢这个

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


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

然后,您可以在这两个视图中单独进行验证摘要!

相关问题