2013-12-19 29 views
2

我想建立可以執行這個邏輯的幫助一個助手:MVC 4 - 建立一個訪問的ViewData

if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Any()) 
{ 
    <div class="note note-danger"> 
     <h4 class="block">Errors</h4> 
     <p>@Html.ValidationSummary()</p> 
    </div> 
} 

這將需要訪問ViewData的Html.ValidationSummary

這些是否需要發送到幫助程序,幫助程序可以通過某些基類以某種方式訪問​​它們?

我的助手:

public static class ValidationSummaryHelper 
{ 
    public static HtmlString Summary(???) 
    { }} 
+0

這是一個剃刀幫手嗎? –

回答

1

相同在C#

public static class ValidationExtensions 
{ 
     public static MvcHtmlString AddCustomValidationSummary(this HtmlHelper htmlHelper) 
     { 
      string result = ""; 

      if (htmlHelper.ViewData.ModelState[""] != null && htmlHelper.ViewData.ModelState[""].Errors.Any()) 
      { 
       result = "<div class='note note-danger'><h4 class='block'>Errors</h4><p>" + htmlHelper.ValidationSummary().ToString() + "</p></div>"; 
      } 

      return new MvcHtmlString(result); 
     } 
} 
+0

人們可能會問爲什麼我發佈這個,並決定downvote。只是供參考我認爲與主要問題的區別;方法參數在C#中與VB相比是截然不同的。 –

+0

是的,我確實收到了Dan-o的回答。 –

3

我不知道C#它的語法,但在VB中它應該是這樣的:

<Extension> 
Public Function AddCustomValidationSummary(htmlHelper As HtmlHelper) As MvcHtmlString 
    Dim result As String = String.Empty 

    If (htmlHelper.ViewData.ModelState("") Is Nothing) AndAlso (htmlHelper.ViewData.ModelState("").Errors.Any()) Then 
     result = "<div class='note note-danger'><h4 class='block'>Errors</h4><p>" & htmlHelper.ValidationSummary().ToString() & "</p></div>" 
    End If 

    Return New MvcHtmlString(result) 
End Function 

這樣使用它:

@Html.AddCustomValidationSummary()