c# - MVC 4 - 构建访问 ViewData 的 Helper

标签 c# asp.net-mvc asp.net-mvc-4

我正在尝试构建一个可以执行此逻辑的助手:

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

它需要访问 ViewDataHtml.ValidationSummary

是否需要将这些发送到 Helper,Helper 是否可以通过某些基类以某种方式访问​​它们?

我的 helper :

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

最佳答案

我不知道它在 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()

关于c# - MVC 4 - 构建访问 ViewData 的 Helper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20671116/

相关文章:

javascript - MVC4 View 未检测到 JQuery

c# - Windows 10 Visual Studio 2019 IIS Express 无法启动并出现错误 500

c# - 为什么参数名称对 Web Api id 有效而 memberId(均为 int)不起作用

javascript - DOM 异常 : Blocked a frame with origin "http://localhost" from accessing a cross-origin frame

asp.net - MVC 的最佳实践.. ViewModel 绑定(bind)使用接口(interface)示例

asp.net-mvc-4 - 从数据库上传模型时丢失dataAnottation

c# - SignedXml.CheckSignature 在 .NET 4 中失败,但在 .NET 3.5、3 或 2 中有效

c# - 我应该在数据验证期间抛出什么异常

javascript - 如何从输入字段中获取多个值并添加到文本区域?

jquery - 如何在 ASP.NET MVC 4 中自动将录制的音频文件保存到服务器上