本文介绍了创建自定义 Html Helper:MyHelperFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以像这样使用的助手

I would like to create a helper that can be used like

@Html.MyHelperFor(m => m.Name)

这应该返回例如

<span name="Name" data-something="Name"></span>

如果是@Html.MyHelperFor(m => m.MailID)这应该返回

</span>

我认为我应该能够在帮助器方法中访问属性名称来制作这种类型的帮助器.

I should be able to access the Property name in the helper method to make this type of helper ,I think.

我该怎么做?

推荐答案

您可以执行类似的操作(以下内容也需要额外的 HTML 属性).

You can do something like (the following will take additional HTML attributes too).

public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
    var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    string propertyName = data.PropertyName;
    TagBuilder span = new TagBuilder("span");
    span.Attributes.Add("name", propertyName);
    span.Attributes.Add("data-something", "something");

    if (htmlAttributes != null)
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        span.MergeAttributes(attributes);
    }

    return new MvcHtmlString(span.ToString());
}

这篇关于创建自定义 Html Helper:MyHelperFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:54