自Html.ValidationMessageFor不在客户端工作 [英] Customize Html.ValidationMessageFor doesn't work in client side

查看:155
本文介绍了自Html.ValidationMessageFor不在客户端工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC3应用程序的工作,我创建了一个自定义的validationMessage验证一个简单的现场。这种习俗validationMessage只会显示而不是默认的跨度标题和消息的DIV,我有这样的:

I am working on mvc3 application, i have created a custom validationMessage to validate a simple field. This custom validationMessage only show an div with title and message instead of the default span, i have this :

@Html.ValidationMessageCustomFor(model => model.FirstName)

这是code到我的自定义验证:

This is the code to my custom validation:

public static MvcHtmlString ValidationCustomFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
    string propertyName = ExpressionHelper.GetExpressionText(expression);
    string name = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));

    if (helper.ViewData.ModelState[name] == null ||
        helper.ViewData.ModelState[name].Errors == null ||
        helper.ViewData.ModelState[name].Errors.Count == 0)
    {
        return MvcHtmlString.Empty;
    }

    StringBuilder htmlValidation = new StringBuilder();

    htmlValidation.AppendLine("<div>");
    htmlValidation.AppendLine("<table>");
    htmlValidation.AppendLine("<tr>");
    htmlValidation.AppendLine("<td><img src='/Content/Imgages/Error.jpg'></td>");
    htmlValidation.AppendLine("</tr>");
    htmlValidation.AppendLine("<tr>");
    htmlValidation.AppendFormat("<td>{0}</td>", name);
    htmlValidation.AppendLine("</tr>");
    htmlValidation.AppendLine("<tr>");
    htmlValidation.AppendFormat("<td>{0}</td>", helper.ViewData.ModelState[name].Errors[0].ErrorMessage);
    htmlValidation.AppendLine("</tr>");
    htmlValidation.AppendLine("</table>");
    htmlValidation.AppendLine("</div>");

    return MvcHtmlString.Create(htmlValidation.ToString());

}

这工作得很好,当我使用服务器端验证,但是当我主动客户端验证这是行不通的。

This works fine when I use server side validation, but when I active client side validation it doesn't work.

默认Html.ValidationMessageFor是正常工作与客户端验证,但我的自定义Html.ValidationMessageCustomFor不起作用。

The default Html.ValidationMessageFor yes works fine with client side validation, but my custom Html.ValidationMessageCustomFor doesn't work.

您能帮我,任何想法?

我修改我的自定义帮手,我添加了数据valmsg换atrib的跨度,它是code:

I modified my custom helper, I added the "data-valmsg-for" atrib for the span, it is the code :

 public static MvcHtmlString ValidationCustomFor2<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        string propertyName = ExpressionHelper.GetExpressionText(expression);
        string name = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));

        if (helper.ViewData.ModelState[name] == null ||
            helper.ViewData.ModelState[name].Errors == null ||
            helper.ViewData.ModelState[name].Errors.Count == 0)
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("span");
        tag.Attributes.Add("class", "field-validation-error");
        tag.Attributes.Add("data-valmsg-for", name);
        tag.Attributes.Add("data-valmsg-replace", "true");

        var text = tag.ToString(TagRenderMode.StartTag);
        text += "<b>My custom html</b>";
        text += tag.ToString(TagRenderMode.EndTag);


        return MvcHtmlString.Create(text);

    }

但它不会出现,它看起来我应该做的从客户端的东西,但我不知道是什么?任何想法吗?

But it doesn't appear, it looks I should do something from the client side, but I don't know WHAT? Any ideas please?

推荐答案

在ASP.NET MVC3验证同时使用服务器端和客户端的方式工作。

The ASP.NET MVC3 validation works using both server-side and client-side methods.

在编写服务器端code到(在你的helper方法等)验证信息添加到呈现的页面,当请求实际发送到服务器的code时才会激活,而客户端机端验证,当启用时,prevents被发送回服务器的请求。

When you write server-side code to add validation messages to the rendered page (like in your helper method), the code is only invoked when the request is actually sent to the server, while the client-side validation, when enabled, prevents the request from being sent back to the server.

默认实现MVC3客户端验证使用一种叫做非侵入式JavaScript验证技术的工作原理,通过添加一些数据 - 属性页面,然后找到和操作的显着在JavaScript元素。

Default implementation of MVC3 client-side validation works using a technique called Unobtrusive JavaScript validation, by adding some data- attributes to the page, and then finding and manipulating the marked elements in the JavaScript.

有关理解不显眼的JavaScript验证,试图寻找它,有一吨的资源在那里。例如:

For understanding the Unobtrusive JavaScript validation, try searching for it, there's a ton of resources out there. For example:

HTTP://www.$c$cproject.com/KB/ ASPNET / CustomClientSideValidatio.aspx

在你的情况,当你想指定显示验证消息,你应该标记与数据valmsg换属性的HTML元素。例如:

In your case, when you want to specify where to display the validation message, you should mark the HTML element with a data-valmsg-for attribute. For example:

<SPAN data-valmsg-for="id_of_the_input_to_validate"></span>

验证的JavaScript将寻找上述属性,并在情况下,输入无效验证信息填写 SPAN 。同样,这种情况发生的形式回发前,让你的服务器端code,显示验证消息不会被调用,因为验证$ P $从提交pvents的形式。

The validation JavaScript will look for the above attribute and fill the SPAN with the validation message in case the input is not valid. Again, this happens before the postback of the form, so your server-side code that shows the validation message is never called, because the validation prevents the form from submitting.

下面是从实际的验证消息帮手列入MVC3一个code片断:

Here's a code snippet from the actual validation message helper included in the MVC3:

TagBuilder builder = new TagBuilder("span"); 
...
if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) {
    builder.MergeAttribute("data-valmsg-for", modelName); 
    builder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant());
} 


编辑:回答您的问题编辑:


Reply to your edited question:

第一次呈现页面时,你的第一个如果真正(有没有验证错误消息渲染),从而将返回一个空字符串。你的页面不会有任何的数据 - 属性在其

The first time the page is rendered, your first if is true (there is no validation error messages to render), thus you return an empty string. Your page will not have any of the data- attributes in it.

您应该呈现的&LT;跨度数据valmsg换=...&GT;&LT; / SPAN&GT; 所有的时间,即使你不吨有任何错误信息,从而使JavaScript库知道往哪里放的情况下,它发生在客户端的错误。

You should render the <span data-valmsg-for="..."></span> all the time, even when you don't have any error messages, so that the JavaScript library knows where to put the error in case it happens on the client side.

这篇关于自Html.ValidationMessageFor不在客户端工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆