7

I want to have custom 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.

So the question is how to set correct "name" attribute?

1
  • At you attempting to create an TextBoxFor version for DateTime fields or an EditFor template for a specific field? I think this is the most important factor at the moment. Commented Dec 21, 2012 at 17:28

2 Answers 2

4

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(). Once you have the name from your expression, you can apply it to your div.

GetExpressionText()

Sign up to request clarification or add additional context in comments.

4 Comments

Be careful with this method as it omits 2 things which NameFor() does: 1) attribute encoding and 2) name qualification. See the MVC source, where the name is further qualified by calling: html.ViewData.TemplateInfo.GetFullHtmlFieldName(name)
Cool! Exactly what I wanted.
@TimMedora - what version of mvc is that for? I see it in the current version of the source, but in the MVC3 app that I pulled my snippet from, I don't see that method. Is it MVC4 only? If you have an MVC4 app, then your solution sounds like the better way to go.
MVC3 RTM, NameExtensions class - After seeing your answer, I was curious how it differed from NameFor(). NameFor() calls GetExpressionText() and passes the result to an overload which returns MvcHtmlString.Create(html.AttributeEncode(html.ViewData.TemplateInfo.GetFullHtmlFieldName(name))); The attribute encoding probably isn't a big deal, but the name qualification can cause problems.
2

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  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.