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. 這是我應該向微軟報告的ASP.NET MVC中的一個錯誤嗎?

回答

4

嘗試一下本作首發: 在頂部每個視圖,你需要確保你有一個可用的形式背景 -

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

我居然把這個在我的_ViewStart.cshtml因爲AJAX加載視圖將需要此驗證有時工作正常(加上一些其他代碼) - 但試試看你的問題

我相信你的問題是如果一個視圖沒有Ajax.BeginForm或Html.BeginForm在視圖本身 - 那麼助手不會發射t他數據val屬性。

+0

哇,很好的呼籲。我把'FormContext'代碼放在我的_ViewStart中,它像一個魅力一樣工作。有一件事讓我感到神祕...爲什麼從cshtml文件生成html的引擎只是將所有的佈局平鋪到一個文件中,然後做任何剩餘的處理?這將確保您獲得相同的結果,無論您是否具有嵌套佈局。不過,至少該解決方法很簡單。謝謝! – devuxer 2011-05-06 04:45:06

+0

可能是因爲幫助者認爲你應該對任何需要進行驗證的表單都有一個表單,因爲驗證需要表單發佈......雖然在某些情況下,我認爲它不適用。就像html助手的行爲與您在post後重新顯示數據時的想法略有不同:http://stackoverflow.com/questions/3544663/updating-value-provider-prior-to-tryupdatemodel/3673915#3673915 – 2011-05-06 04:50:25