开发者

How to write a custom override for LabelFor in asp mvc 2?

Hi I have a piece of code which gives an error.

<%=Html.开发者_开发问答LabelFor(m => m.Id, new { @Class = "textbox-medium" })%>

Error:

No overload for method 'LabelFor' takes '2' arguments.

Does anyone know how to resolve this ?

Thanks


Maybe something among the lines:

public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> ex,
        object htmlAttributes
    )
    {
        var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(ex, htmlHelper.ViewData);
        var htmlFieldName = ExpressionHelper.GetExpressionText(ex);
        var labelText = metadata.DisplayName;
        if (string.IsNullOrEmpty(labelText))
        {
            labelText = htmlFieldName.Split('.').Last();
        }
        if (string.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        var tagBuilder = new TagBuilder("label");
        var id = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
        tagBuilder.Attributes.Add("for", id);
        var attributes = new RouteValueDictionary(htmlAttributes);
        tagBuilder.MergeAttributes(attributes);
        tagBuilder.SetInnerText(labelText);
        return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
    }
}

and then:

<%= Html.LabelFor(x => x.Id, new { @class = "textbox-medium" }) %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜