我正在尝试构建一个可以执行此逻辑的帮助程序:
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
这些是否需要发送到Helper,Helper可以通过某种基类以某种方式访问它们吗?
我的助手:
public static class ValidationSummaryHelper
{
public static HtmlString Summary(???)
{ }}
答案 0 :(得分: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()
答案 1 :(得分:2)
在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);
}
}