65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET MVC 自定义验证消息助手

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (3投票s)

2015年10月24日

CPOL

1分钟阅读

viewsIcon

21735

downloadIcon

362

编写 ASP.NET MVC 中的自定义验证消息助手扩展

引言

我之前写过一篇关于 在 ASP.NET MVC 中创建自定义 HTML 助手 的文章,强调了我们可以根据需要编写自定义 HTML 助手扩展,以便在整个应用程序中重用它们,而不是在视图中编写纯 HTML。

那篇文章中的示例使用了 ActionLink,今天我将介绍如何实现自定义验证消息助手。我希望修改应用程序中显示的验证消息,使其在必填字段前面显示 *,并将错误消息显示在其工具提示中,如下所示:

为此,在项目中添加一个类,并添加一个扩展方法,该方法将呈现用于显示错误消息的自定义 HTML

namespace CustomValidationMessageHelper.Helpers
{
    public static class Validator
    {
        public static MvcHtmlString MyValidationMessageFor<TModel, 
		TProperty>(this HtmlHelper<TModel> helper, 
		Expression<Func<TModel, TProperty>> expression)
        {
            TagBuilder containerDivBuilder = new TagBuilder("div");
            containerDivBuilder.AddCssClass("tip_trigger");
            containerDivBuilder.InnerHtml = "*";

            TagBuilder midDivBuilder = new TagBuilder("div");
            midDivBuilder.AddCssClass("classic");
            midDivBuilder.AddCssClass("tip");
            midDivBuilder.InnerHtml = helper.ValidationMessageFor(expression).ToString();

            containerDivBuilder.InnerHtml += midDivBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(containerDivBuilder.ToString(TagRenderMode.Normal));
        }
    }
}

然后,在 CSS 文件中定义以下 CSS,在我的例子中是 site.css,或者您可以将其添加到视图中

.validated {
    border-color: #DCE4EC !important;
}

textarea, input[type="text"], input[type="password"], 
input[type="datetime"], 
	input[type="datetime-local"], input[type="date"], 
	input[type="month"], 
	input[type="time"], input[type="week"], 
	input[type="number"], input[type="email"], 
	input[type="url"], input[type="search"], 
	input[type="tel"], input[type="color"], 
	.uneditable-input {
    padding: 3px 3px;
    border: 1px solid #DCE4EC;
}
        
.tip {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #808080;
    border-radius: 10px;
    box-shadow: 0 1px 10px rgba(32, 32, 32, 0.5);
    color: red;
    display: none;
    font-size: 12px;
    font-style: normal;
    margin-left: 10px;
    margin-top: -24px;
    padding: 4px;
    position: absolute;
    z-index: 999999;
}

.tip_trigger {
    width: 10px;
    float: right;
    color: red;
    margin-left: 3px;
}

现在我们需要添加客户端代码,我已在 js 文件中或直接在视图中用 jquery 编写,在我的例子中,它在 CustomValidation.js 文件中

$(document).ready(function () {
    //Tooltips
    var tip;
    $(".tip_trigger").hover(function () {
        console.log("hovered");
        tip = $(this).find('.tip');
        console.log($(this).find('.tip').find('span').html())
        if ($(this).find('.tip').find('span').html() != '') {
            $(this).find('.tip').show(); //Show tooltip
        }
    }, function () {
        $(this).find('.tip').hide(); //Hide tooltip 
    });

    ////Required fields
    $('input').each(function () {
        var req = $(this).attr('data-val-required');
        if (undefined != req) {
            $(this).css("border-color", "#DA9BA2")

        }
        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
    });

    $('input').blur(function () {

        if ($(this).val() != '') {

            $(this).addClass("validated");
        }
        else {

            $(this).css("border-color", "#DA9BA2")
        }
    });
});

现在在视图中,在视图的 head 部分添加对相关 js 和 css 文件的引用

    <link href="@Url.Content("~/Content/site.css")" 
    	rel="stylesheet"/>
    <script src="@Url.Content("~/Scripts/jquery-1.9.1.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" 
    	type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" 
    	type="text/javascript">
    </script>
    <script src="@Url.Content("~/Scripts/CustomValidation.js")" 
    	type="text/javascript"></script>

现在在您的视图中,添加命名空间的 using 语句,现在您可以在视图中访问 Helper 方法

@model CustomValidationMessageHelper.ViewModels.SignUpViewModel
@using CustomValidationMessageHelper.Helpers
@{
    Layout = null;
}

@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control input-sm" })
@Html.MyValidationMessageFor(model => model.FirstName)

可以从 这里 下载示例项目。

© . All rights reserved.