1

这是我的原始创建页面(无嵌套) - 客户端验证有效

@model TennisClub.ViewModels.ClubMember.EditorModel
@{
    ViewBag.Title = "New Club Member";
    ViewBag.LegendTitle = "Club Member";
}
<h2>@ViewBag.Title</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Errors were found on the form. Please correct all errors and try again.")
    <fieldset>
        <legend>@ViewBag.LegendTitle</legend>
        @Html.EditorForModel()
        <p><input type="submit" value="Create" /></p>
    </fieldset>
}
<div>@Html.ActionLink("Back to List", "Index")</div>

这是我的新创建页面(嵌套)-客户端验证失败

@model TennisClub.ViewModels.ClubMember.EditorModel
@{
    Layout = "~/Views/Shared/StandardLayouts/Create.cshtml";
    ViewBag.Title = "New Club Member";
    ViewBag.LegendTitle = "Club Member";
}
@Html.EditorForModel()
@if (ViewBag.CanUserAccessRestrictedContent)

这是上面页面使用的布局(StandardLayouts/Create.cshtml)

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true, "Errors were found on the form. Please correct all errors and try again.")
    <fieldset>
        <legend>@ViewBag.LegendTitle</legend>
        @RenderBody()
        <p><input type="submit" value="Create" /></p>
    </fieldset>
}
<div>@Html.ActionLink("Back to List", "Index")</div>

讨论

据我所知,除了客户端验证外,使用嵌套方法一切正常。当我查看页面源代码时,脚本引用在那里(验证和验证.unobtrusive),但 html 中没有显示验证属性。如果我不使用嵌套布局,则脚本引用和验证属性都在那里。

无论我使用标准的基于属性的验证还是 FluentValidation,我都会得到相同的结果。

问题

  1. 我做布局嵌套的方式有什么不正确的吗?除了这个问题外,它似乎工作正常,但也许我正在以非标准方式做事。

  2. web.config 中是否有设置或我需要更改的其他位置以使客户端验证适用于嵌套超过一层深度的页面?

  3. 这是我应该向 Microsoft 报告的 ASP.NET MVC 中的错误吗?

4

1 回答 1

4

初学者试试这个:在顶部的每个视图中,您需要确保您有一个可用的表单上下文 -

@{
if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext();
}

我实际上把它放在了我的 _ViewStart.cshtml 中,因为 ajax 加载的视图有时需要它来验证才能正常工作(加上一些其他代码) - 但试试你的问题

我相信您的问题是,如果视图本身没有 Ajax.BeginForm 或 Html.BeginForm - 那么助手将不会发出 data-val 属性。

于 2011-05-06T03:14:10.670 回答