0

我正在使用 ASP.NET MVC 2,但我认为我没有听说过 MVC 3 或 4 中已修复此问题,但无论如何:

这是我的测试视图代码:

<br />
<%= Html.LabelFor( m => m.FieldFoo ) %>
<%= Html.TextBoxFor( m => m.FieldFoo ) %>

<br />
<%= Html.LabelFor( m => m.CustomFieldValues[0].Value ) %>
<%= Html.TextBoxFor( m => m.CustomFieldValues[0].Value ) %>

这就是渲染的内容:

<br />
<label for="FieldFoo">Foo?</label>
<input id="FieldFoo" name="FieldFoo" type="text" value="foo" />

<br />
<label for="CustomFieldValues[0]_Value">Value</label>
<input id="CustomFieldValues_0__Value" name="CustomFieldValues[0].Value" type="text" value="bar" />

发现差异:索引属性CustomFieldValues没有将其[]字符替换_for=""属性。为什么?

我走进了LabelFor代码,看到它调用了,html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));而 MVC 的内部InputHelper有自己的逻辑,TagBuilder.CreateSanitizedId()这解释了为什么它得到不同的id=""属性值。

在 MVC 2 中是否有任何解决方法?

4

1 回答 1

0

ASP.NET MVC 2 没有带有 htmlAttributes 参数的 LabelFor 扩展方法。请参阅此博客文章。我们可以创建一个扩展来添加此参数并解决您的上述问题。这是示例,

public static class MyTagBuilder
{
    public static string CreateSanitizedId(string originalId)
    {
        return CreateSanitizedId(originalId, HtmlHelper.IdAttributeDotReplacement);
    }

    public static string CreateSanitizedId(string originalId, string invalidCharReplacement)
    {
        if (String.IsNullOrEmpty(originalId))
        {
            return null;
        }

        if (invalidCharReplacement == null)
        {
            throw new ArgumentNullException("invalidCharReplacement");
        }

        char firstChar = originalId[0];
        if (!Html401IdUtil.IsLetter(firstChar))
        {
            // the first character must be a letter
            return null;
        }

        StringBuilder sb = new StringBuilder(originalId.Length);
        sb.Append(firstChar);

        for (int i = 1; i < originalId.Length; i++)
        {
            char thisChar = originalId[i];
            if (Html401IdUtil.IsValidIdCharacter(thisChar))
            {
                sb.Append(thisChar);
            }
            else
            {
                sb.Append(invalidCharReplacement);
            }
        }

        return sb.ToString();
    }

    private static class Html401IdUtil
    {
        private static bool IsAllowableSpecialCharacter(char c)
        {
            switch (c)
            {
                case '-':
                case '_':
                case ':':
                    // note that we're specifically excluding the '.' character
                    return true;

                default:
                    return false;
            }
        }

        private static bool IsDigit(char c)
        {
            return ('0' <= c && c <= '9');
        }

        public static bool IsLetter(char c)
        {
            return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
        }

        public static bool IsValidIdCharacter(char c)
        {
            return (IsLetter(c) || IsDigit(c) || IsAllowableSpecialCharacter(c));
        }
    }

}
public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
    {
        return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
    }
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (String.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("label");
        tag.MergeAttributes(htmlAttributes);
        tag.Attributes.Add("for", MyTagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
        tag.SetInnerText(labelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}


<%@ Import Namespace="NameSpaceOfTheExtensionMethodClass" %>


<%= Html.LabelFor(m => m.CustomFieldValues[0].Value, new { })%>
<%= Html.TextBoxFor( m => m.CustomFieldValues[0].Value )%>
于 2013-03-17T12:31:30.387 回答