4

问题

我正在尝试在 MVC 中实现 HTML5/jQuery 模型,但遇到了我以前从未遇到过的问题;它似乎使用 Html.TextBoxFor、Html.PasswordFor 和其他都自动编码任何传递的 HTML 属性。

例子

以下面一行为例:

@Html.TextBoxFor(m => m.Pin, new { data_regexp="<\\d{4}>" })

此代码将用于验证信用卡上的 PIN 码,我需要使用 data-regexp 模式来传递适当的正则表达式。我希望输出如下:

<input data-regexp="<\d{4}>" id="Pin" type="text" />

相反,它似乎是从内置扩展中调用 HtmlAttributeEncode ( http://msdn.microsoft.com/en-us/library/wdek0zbf.aspx ),从而产生以下编码输出:

<input data-regexp="&lt;\d{4}>" id="Pin" type="text" />

所需的解决方案说明

除了编写自己的扩展之外,我还有其他选择吗?使用其他形式的验证不是一种选择,这个例子只是为了展示手头的问题——我还有其他几个例子,我需要打印原始 HTML,而不是编码版本。

编辑:使用 Html.Raw 或 HttpUtility.Decode 没有影响。编码发生在应用这些中的任何一个之后。

4

3 回答 3

2

弄清楚了。我添加了以下类:

namespace MyProjectName.Extensions
{
    public class HtmlAttributeNoEncoding : HttpEncoder
    {
        protected override void HtmlAttributeEncode(string value, TextWriter output)
        {
            output.Write(value);
        }
    }
}

并修改了我的网络配置:

<system.web>
    ...
    <httpRuntime targetFramework="4.5" encoderType="MyProjectName.Extensions.HtmlAttributeNoEncoding"/>
    ... 
</system.web>
于 2013-09-05T20:13:07.943 回答
1

试试这个自定义 HTMLHelper 扩展:

自定义 HtmlHelper 扩展:

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MvcApplication.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static IHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, object dataAttribute)
        {
            MvcHtmlString textBoxFor = InputExtensions.TextBoxFor<TModel, TProperty>(htmlHelper, expression, htmlAttributes);

            string stringDataAttributes = string.Empty;
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(dataAttribute))
            {
                stringDataAttributes+= string.Format("data-{0}=\"{1}\" ", property.Name, property.GetValue(dataAttribute));
            }

            string textBoxForText = textBoxFor.ToHtmlString();
            string textBoxWithData = textBoxForText.Insert(textBoxForText.IndexOf("/>"), stringDataAttributes);

            return htmlHelper.Raw(textBoxWithData);
        }
    }
}

cshtml:

@Html.MyTextBoxFor(m => m.Pin, null, new { regexp = "<\\d{5}>" })

结果:

<input id="Pin" name="Pin" type="text" value="" data-regexp="<\d{5}>" />
于 2013-09-05T18:12:34.240 回答
0

如果您在模型上使用数据注释,它将起作用。

[RegularExpression(@"\d{4}", ErrorMessage="4 digit PIN required")]
public string Pin { get; set; }

然后,您可以只使用 TextboxFor 而不传递额外的属性:

@Html.TextBoxFor(m => m.Pin)

这将返回 html 为:

data-val-regex="4 digit PIN required" data-val-regex-pattern="\d{4}"
于 2013-09-05T18:07:41.063 回答