如何扩展Html.ValidationMessage,这样我可以包括图像的错误? [英] How do I extend Html.ValidationMessage so that I can include an image as the error?

查看:291
本文介绍了如何扩展Html.ValidationMessage,这样我可以包括图像的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,以减少下列code。下面code的作品,但它是不是很整齐等。

I would like to reduce the following code. The below code works, however it is not very tidy etc.

    <label for="Name">Name:</label><%= Html.TextBox("Name")%><% 
    if (!string.IsNullOrEmpty(Html.ValidationMessage("Name"))) {
    	string Error = HtmlRemoval.StripTags(Html.ValidationMessage("Name")); %>
        <img src="Error.gif" alt="Error" title="<%= Error %>" /><%
    }
    %>

我已阅读,我需要延长的HTML帮助,这样我可以返回一个包含默认元素和文本错误的文本的图像来代替。

I have read that I need to extend the Html helper so that I can return an image instead of the text containing the default element and textual error.

我似乎无法找到我会怎样做到这一点的任何文章或一般建议。我还是很新的ASP.NET MVC。任何意见将大大AP preciated。

I can't seem to find any articles or general advice on how I would accomplish this. I am still very new to ASP.NET MVC. Any advice would be greatly appreciated.

推荐答案

您可以扩展的HtmlHelper这样的:

You can extend HtmlHelper like:

public static class CustomHtmlHelper {

  public static string ValidationImage(this HtmlHelper helper, string name) {
    if (helper.ViewData.ModelState[name] == null || helper.ViewData.ModelState[name].Errors == null) {
      return String.Empty;
    }
    TagBuilder tag = new TagBuilder("img");
    tag.Attributes.Add("src", "Error.gif");
    tag.Attributes.Add("alt", "Error");
    tag.Attributes.Add("title", helper.ViewData.ModelState[name].Errors[0].ErrorMessage);
    return tag.ToString(TagRenderMode.SelfClosing);
  }

}

然后在你的页面导入包含扩展方法的类

Then in your page import the class containing the extension method

<%@ Import Namespace="CustomHtmlHelperNamespace" %>

然后添加以下到您的网页:

Then add the following to your page:

<label for="Name">Name:</label>
<%= Html.TextBox("Name")%>
<% Html.ValidationImage("Name") %>

更多关于延长HtmlHelper的尝试这里但基本上这个扩展的HtmlHelper,检查视图状态在名称解析(名称,在您的案件)值的一个错误,如果它包含一个错误产生渲染图像所需的HTML。对于图像的title属性将包含验证消息字段名称

For more on extending HtmlHelper try here but basically this extends HtmlHelper, checks the ViewState for a an error on the value parsed in name ("Name" in your case) and if it contains an error generates the HTML needed to render the image. The title attribute for the image will contain the validation message for field "Name"

这篇关于如何扩展Html.ValidationMessage,这样我可以包括图像的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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