MVC不显眼的验证仅适用于一个嵌套模型

时间:2012-05-08 10:42:29

标签: asp.net-mvc-3 nested-forms unobtrusive-validation

我有一个由嵌套模型组成的表单,如下所示:

foreach (var item in Model)
   {
    <h3>
        @item.StageDescription
    </h3>
    <div class="well">
        <table id="Item@(item.ID)" class="WizardOption">
            <thead>
                <tr>
                    <some headings here />
                </tr>
            </thead>
            <tbody>
                @Html.EditorFor(m => item.WizardOptions,"","WizardOptions",null)
            </tbody>
        </table>
    </div>
}

WizardOption类具有必填字段调用显示值:

public class WizardOptionMetaData {
        [Required]
        public string DisplayValue { get; set; }
}

这适用于第一个表,如果我将DisplayValue字段留空,我会收到错误:“DisplayValue字段是必需的。”并呈现以下标记:

<input class="description-box" data-val="true" data-val-required="The DisplayValue field is required." id="WizardOptions_0__DisplayValue" name="WizardOptions[0].DisplayValue" type="text" value="">

但是第一个之后的任何表都没有正确呈现验证:

<input class="description-box" id="WizardOptions_1__DisplayValue" name="WizardOptions[1].DisplayValue" type="text" value="">

我哪里错了?

1 个答案:

答案 0 :(得分:0)

在我发布问题之后找到了我没有找到的问题的答案:

ASP.NET MVC 3: Generate unobtrusive validation when BeginForm is on the layout

@{
     var originalContext = ViewContext.FormContext;
     ViewContext.FormContext = new FormContext();
} 

<!-- This will generate proper HTML5 data-* validation attributes -->
@Html.TextBoxFor(x => x.Prop1)
     @Html.ValidationMessageFor(x => x.Prop1)

     @Html.TextBoxFor(x => x.Prop2)
     @Html.ValidationMessageFor(x => x.Prop2)

@{
     ViewContext.FormContext = originalContext;
 }