自定义验证摘要模板 Asp.net MVC 3

发布于 2024-11-04 18:07:34 字数 556 浏览 2 评论 0原文

我正在使用 Asp.Net MVC3 进行一个项目

,在视图中我有 @Html.ValidationSummary(true) 并且通常它会生成

<div class="validation-summary-errors">
    <ul>
        <li>Something bad Happened!</li>
    </ul>
</div>

How can I Extend this ValidationSummary to MyValidationSummary 并生成 Html 代码模板像这样:

<div class="notification warning"> 
    <span></span> 
    <div class="text"> <p>Something bad Happened!</p> </div> 
</div>

I am working on a project with Asp.Net MVC3

In a View I have @Html.ValidationSummary(true) and as usually it produces

<div class="validation-summary-errors">
    <ul>
        <li>Something bad Happened!</li>
    </ul>
</div>

How can I extend this ValidationSummary to MyValidationSummary and produces the Html Code template something like this:

<div class="notification warning"> 
    <span></span> 
    <div class="text"> <p>Something bad Happened!</p> </div> 
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

递刀给你 2024-11-11 18:07:35

我只想显示顶层消息,而不是其他任何内容。我们已经在下面的字段旁边进行了验证。使用 @Leniel-Macaferi 的解决方案,这就是我所做的,使其与 jQuery 验证一起工作:(添加了 style="display: none;")

<div class="@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors")"
     data-valmsg-summary="true">
    <div>
        There are still some fields not filled in before we can submit this. Please correct.
    </div>
    <div style="display: none;">
        <ul>
            @foreach (var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
</div>

I wanted to show just top-level message and nothing else. We already have validation next to the fields below. Working off @Leniel-Macaferi's solution this is what I did to make it work with jQuery validation: (added style="display: none;")

<div class="@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors")"
     data-valmsg-summary="true">
    <div>
        There are still some fields not filled in before we can submit this. Please correct.
    </div>
    <div style="display: none;">
        <ul>
            @foreach (var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
</div>
笑饮青盏花 2024-11-11 18:07:34

我的方法是使用自定义 ValidationSummary.cshtml

@model ModelStateDictionary

@if(!Model.IsValid)
{
    <div class="validation-summary-errors">
        <ul>
            @foreach (var modelError in 
                     Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
}

将此部分视图放入共享文件夹中并从代码中引用它:

@Html.Partial("_ValidationSummary", ViewData.ModelState);

这样您就可以完全控制 html。

My approach is to use a custom ValidationSummary.cshtml:

@model ModelStateDictionary

@if(!Model.IsValid)
{
    <div class="validation-summary-errors">
        <ul>
            @foreach (var modelError in 
                     Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
}

Put this partial view in your Shared folder and refer to it from your code:

@Html.Partial("_ValidationSummary", ViewData.ModelState);

This way you remain in full control of your html.

小霸王臭丫头 2024-11-11 18:07:34

这个问题详细介绍了编写自定义验证摘要。

编辑
这将实现您想要的功能:

public static class LinqExt 
{
    public static string MyValidationSummary(this HtmlHelper helper, string validationMessage="")
    {
        string retVal = "";
        if (helper.ViewData.ModelState.IsValid)
            return "";

        retVal += "<div class='notification-warnings'><span>";
        if (!String.IsNullOrEmpty(validationMessage))
            retVal += helper.Encode(validationMessage);
        retVal += "</span>";
        retVal += "<div class='text'>";
        foreach (var key in helper.ViewData.ModelState.Keys) 
        {
            foreach(var err in helper.ViewData.ModelState[key].Errors)
                retVal += "<p>" + helper.Encode(err.ErrorMessage) + "</p>";
        }
        retVal += "</div></div>";
        return retVal.ToString();
    }
}

代码是不言自明的;只需枚举模型状态错误并将错误包装在您选择的 dom 元素中。有一个错误,如果我像这样使用它:

<%:Html.MyValidationSummary()%>

它将在页面上将 html 标签显示为文本而不是呈现它。

<%=Html.MyValidationSummary()%>

这很好用。

This question details the procedure of writing custom validation summary.

EDIT
This will do what you want:

public static class LinqExt 
{
    public static string MyValidationSummary(this HtmlHelper helper, string validationMessage="")
    {
        string retVal = "";
        if (helper.ViewData.ModelState.IsValid)
            return "";

        retVal += "<div class='notification-warnings'><span>";
        if (!String.IsNullOrEmpty(validationMessage))
            retVal += helper.Encode(validationMessage);
        retVal += "</span>";
        retVal += "<div class='text'>";
        foreach (var key in helper.ViewData.ModelState.Keys) 
        {
            foreach(var err in helper.ViewData.ModelState[key].Errors)
                retVal += "<p>" + helper.Encode(err.ErrorMessage) + "</p>";
        }
        retVal += "</div></div>";
        return retVal.ToString();
    }
}

The code is self explanatory; just enumerating through modelstate errors and wrapping errors in dom element of your choice. There is an error that is if i use it like:

<%:Html.MyValidationSummary()%>

It will display html tags on the page as text rather than rendering it.

<%=Html.MyValidationSummary()%>

This works fine.

转角预定愛 2024-11-11 18:07:34

基于 flos 的答案,我使其与 Microsoft 的 jQuery Unobtrusive Validation 兼容,并添加了 Bootstrap 的 3 面板样式。这是新代码:

@model ModelStateDictionary

<div class="@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors") panel panel-danger"
     data-valmsg-summary="true">
    <div class="panel-heading">
        Please, correct the following errors:
    </div>
    <div class="panel-body">
        <ul>
            @foreach(var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
</div>

您可以在此处详细阅读:

使用 Bootstrap 3 面板创建自定义 ASP.NET MVC @Html.ValidationSummary 样式

我还创建了一个示例 ASP.NET MVC 项目来显示此自定义 ValidationSummary 的实际应用。在这里获取:

https://github.com/leniel/AspNetMvcCustomHtmlValidationSummary

Building upon flos's answer, I made it compatible with Microsoft's jQuery Unobtrusive Validation and added Bootstrap's 3 panel styling. Here's the new code:

@model ModelStateDictionary

<div class="@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors") panel panel-danger"
     data-valmsg-summary="true">
    <div class="panel-heading">
        Please, correct the following errors:
    </div>
    <div class="panel-body">
        <ul>
            @foreach(var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
</div>

You can read about it in full detail here:

Creating a custom ASP.NET MVC @Html.ValidationSummary styled with Bootstrap 3 panel

I also created a sample ASP.NET MVC project to show this custom ValidationSummary in action. Get it here:

https://github.com/leniel/AspNetMvcCustomHtmlValidationSummary

我要还你自由 2024-11-11 18:07:34

只是在这里发布我的答案,因为它对我来说效果很好;)

我使用一个简单的扩展方法,该方法接受 MvcHtmlString 并将其解码回 HTML:

    public static MvcHtmlString ToMvcHtmlString(this MvcHtmlString htmlString)
    {
        if (htmlString != null)
        {
            return new MvcHtmlString(HttpUtility.HtmlDecode(htmlString.ToString()));
        }
        return null;
    }

为了深入了解这一点,我将验证摘要助手添加到我的chstml 像这样:

@Html.ValidationSummary(true).ToMvcHtmlString()

这意味着,我可以将自定义 HTML 添加到我的验证摘要中:

ModelState.AddModelError("", "<p>This message can have html in it</p>");

我什至可以将自定义 HTML 添加到我的字段验证消息中:

ModelState.AddModelError("MyField", "<p>This message can have html in it</p>");

并让我的字段验证消息与 HTML 一起使用:

@Html.ValidationMessageFor(model => model.MyField).ToMvcHtmlString();

Just posting my answer here because it's working well for me ;)

I use a simple extension method that takes an MvcHtmlString and decodes it back to HTML:

    public static MvcHtmlString ToMvcHtmlString(this MvcHtmlString htmlString)
    {
        if (htmlString != null)
        {
            return new MvcHtmlString(HttpUtility.HtmlDecode(htmlString.ToString()));
        }
        return null;
    }

To plumb this in, I add the validation summary helper to my chstml like this:

@Html.ValidationSummary(true).ToMvcHtmlString()

This means, I can add custom HTML to my validation summaries:

ModelState.AddModelError("", "<p>This message can have html in it</p>");

And I can even add custom HTML to my field validation messages:

ModelState.AddModelError("MyField", "<p>This message can have html in it</p>");

And to get my field validation messages to work with HTML:

@Html.ValidationMessageFor(model => model.MyField).ToMvcHtmlString();
清旖 2024-11-11 18:07:34

添加相关样式:

.field-validation-error {
    color: #b94a48;
}

.field-validation-valid {
    display: none;
}

input.input-validation-error {
    border: 1px solid #b94a48;
}

input[type="checkbox"].input-validation-error {
    border: 0 none;
}

.validation-summary-errors {
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}

Adding related styles:

.field-validation-error {
    color: #b94a48;
}

.field-validation-valid {
    display: none;
}

input.input-validation-error {
    border: 1px solid #b94a48;
}

input[type="checkbox"].input-validation-error {
    border: 0 none;
}

.validation-summary-errors {
    color: #b94a48;
}

.validation-summary-valid {
    display: none;
}

时光无声 2024-11-11 18:07:34

我只需要为服务器端验证做一些类似的事情(例如检查文件内容),并且最终完全篡夺了 @Html.ValidationSummary 并做了一些相当不错的小工作。

我们有一个扩展 Controller 的 BaseController 类,并且在内部我们出于多种目的重写了 OnActionExecuting 方法。
我们在 ViewBag 中为错误消息创建一个新列表,并确保在任何操作运行之前它已初始化。然后我们可以添加要显示的错误,并显示在屏幕上。

出于这个问题的目的,它看起来像这样。

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (ViewBag.ErrorsList == null)
        {
            ViewBag.ErrorsList = new List<string>();
        }
    }
}

然后在我们的 _Layout.cshtml 中添加以下内容到 @RenderBody()

@if(ViewBag.ErrorsList.Count > 0)
{
    <div class="container margin-top-10 alert alert-danger">
        <h3><i class="glyphicon glyphicon-warning-sign"></i></h3><br/>
        @foreach (string error in @ViewBag.ErrorsList)
        {
            @error <br/>
        }
    </div>
    @RenderBody()
}

上方 现在,每当服务器端发生错误时,我们希望将其显示为验证错误消息,我们只需将其添加到我们的 ViewBag.ErrorsList 中

ViewBag.ErrorsList.Add("Something bad happened...");

,瞧,这是您服务器的一个自定义容器带有您想要的任何样式的侧面验证错误消息,错误以与 ValidationSummary 相同的方式传递。

I've just had to do something similar for server side validation only ( e.g checking file contents) and have ended up completely usurping the @Html.ValidationSummary altogether with quite a nice little work around.

We have a BaseController class that extends Controller, and inside we override the OnActionExecuting method for several purposes.
We create a new list in ViewBag for our error messages and ensure before any action runs it is initialized. Then we can add our errors to be displayed to it, and display on screen.

For the purposes of this question it would look like this.

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (ViewBag.ErrorsList == null)
        {
            ViewBag.ErrorsList = new List<string>();
        }
    }
}

Then in our _Layout.cshtml add the following above your @RenderBody()

@if(ViewBag.ErrorsList.Count > 0)
{
    <div class="container margin-top-10 alert alert-danger">
        <h3><i class="glyphicon glyphicon-warning-sign"></i></h3><br/>
        @foreach (string error in @ViewBag.ErrorsList)
        {
            @error <br/>
        }
    </div>
    @RenderBody()
}

Now whenever an error occurs server side that we want to display as a validation error message we simply add it to our ViewBag.ErrorsList

ViewBag.ErrorsList.Add("Something bad happened...");

And voila, one custom container for your server side validation error messages with any styles you want on it, with errors passed in the same manner as ValidationSummary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文