How to get the form name for a property

喜夏-厌秋 提交于 2019-12-23 12:27:42

问题


In Razor I know that if you write

@Html.HiddenFor(x => x.PropertyX.PropertyY)

it will generate HTML like:

<input type="hidden" name="PropertyX.PropertyY" value="...">

And (especially) if this was in an Editor Template it might generate this HTML:

<input type="hidden" name="ParentProperty[12].PropertyX.PropertyY" value="...">

How do I get a name for an arbitrary property? I'm assuming there must be some way to do this using MVC infrastructure (perhaps some method or class?)


回答1:


You could write a custom helper for that:

public static class NameExtensions
{
    public static string NameFor<TModel, TProperty>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TProperty>> expression
    )
    {
        var partialName = ExpressionHelper.GetExpressionText(expression);
        return html
            .ViewContext
            .ViewData
            .TemplateInfo
            // You could do the same with GetFullHtmlFieldId
            // if you were interested in the id of the element
            .GetFullHtmlFieldName(partialName);
    }
}

and then:

@Html.NameFor(x => x.PropertyX.PropertyY)


来源:https://stackoverflow.com/questions/7327215/how-to-get-the-form-name-for-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!