简体   繁体   English

如何编写像Html.TextBoxFor这样的自定义ASP.NET MVC HTML Helper并设置正确的name属性

[英]How to write custom ASP.NET MVC HTML Helper like Html.TextBoxFor and set correct name attribute

I want to have custom Html.DateTimePickerFor(a => a.Fields[0].Id, value) 我想要自定义Html.DateTimePickerFor(a => a.Fields[0].Id, value)

so the result should be like this: 所以结果应该是这样的:

<div name="Fields[0].Id"></div>

Currently I use Html.DatetimePicker("Fields[0].Id", value) and it works perfectly, but I wan to generate dynamic name. 目前,我使用Html.DatetimePicker("Fields[0].Id", value) ,并且效果很好,但是我想生成动态名称。

So the question is how to set correct "name" attribute? 那么问题是如何设置正确的"name"属性?

Try this. 尝试这个。 It works for me. 这个对我有用。

    public static MvcHtmlString DateTimePickerFor<TModel, TProp>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProp>> expression, object htmlAttributes)
    {
        string name   = ExpressionHelper.GetExpressionText(expression);
        ... rest of code here
    }

The magic comes from System.Web.Mvc.ExpressionHelper.GetExpressionText() . 魔术来自System.Web.Mvc.ExpressionHelper.GetExpressionText() Once you have the name from your expression, you can apply it to your div. 从表达式中获得名称后,即可将其应用于div。

GetExpressionText() GetExpressionText()

Try something like this (adapted from working code): 尝试这样的事情(改编自工作代码):

public static IHtmlString DateTimePickerFor<TModel, TValue>(
    this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TValue>> expression,

    // other input parameters as needed

) {
    // metadata gives you access to a variety of useful things, such as the
    // display name and required status
    var metadata = ModelMetadata.FromLambdaExpression( expression, helper.ViewData );
    string markup = ""; // markup for your input            

    var name = helper.NameFor( expression ); // getting the name

    return MvcHtmlString.Create( markup  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM