asp net mvc局部视图验证

Jua*_*rin 0 validation asp.net-mvc partial-views

你好你好吗?我正在尝试验证ASP NET MVC中的表单.

我有部分视图"地址",我重用于某些实体,如公司,人员等.

我的问题是,当我提交表单时,只有父视图的控件才会被验证,而局部视图中的控件则不会.

这里有一些代码我希望你可以帮助我

人物观点

@model Entities.Person


@using (Html.BeginForm("Create", "Person", FormMethod.Post))
{

    <table>
        <tr>
            <td>
                @Html.LabelFor(model => model.FirstName)
                <div class="control">
                    @Html.TextBoxFor(model => model.FirstName, new { @maxlength = 7, @class = "numeric"})
                    @Html.ValidationMessageFor(model => model.FirstName)
                </div>
                <div class="spacer-short"></div>
            </td>
            <td>
                @Html.LabelFor(model => model.LastName)
                <div class="control">
                    @Html.TextBoxFor(model => model.LastName, new { @maxlength = 7, @class = "numeric"})
                    @Html.ValidationMessageFor(model => model.LastName)
                </div>
                <div class="spacer-short"></div>
            </td>
        </tr>
    </table>
    @{ Html.RenderAction("Index", "Address", new {id = Model.AddressId});} //Renders the Address form part

    <div class="spacer"></div>
    <button type="submit" data-button="true" data-button-icon="ui-icon-disk" class="">Create</button>
    <button type="button" data-button="true" data-button-icon="ui-icon-circle-close" class="button-cancel">Cancel</button>
}
Run Code Online (Sandbox Code Playgroud)

地址视图

@model Entities.Address


<table>
     <tr>
         <td>
            @Html.LabelFor(model => model.Street)
            <div class="control">
                @Html.TextBox("Address.Street", Model.Street)
                @Html.ValidationMessage("Address.Street")
             </div>
           <div class="spacer-short"></div>
           </td>
           <td>
              @Html.LabelFor(model => model.Number)
              <div class="control">
                @Html.TextBox("Address.Number", Model.Number)
                @Html.ValidationMessage("Address.Number")
             </div>
           <div class="spacer-short"></div>
            </td>
        </tr>
    </table>
Run Code Online (Sandbox Code Playgroud)

然后我为人员和地址字段提供了一些验证元数据([必需])

Dmi*_*try 8

使用@Html.Partial(...)和期望验证错误显示的常见错误是没有将ViewData传递给该部分:

@Html.Partial([ViewName], [EmailAddressObject], ViewData)
Run Code Online (Sandbox Code Playgroud)