Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

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?

like image 822
Sergey Avatar asked Dec 21 '12 17:12

Sergey


People also ask

How do I set the MaxLength for HTML TextBoxFor in MVC?

The MaxLength for TextBoxes is set using the HTML MaxLength attribute using the HtmlAttributes parameter in Html. TextBox and Html. TextBoxFor helper functions.

Which method of HTML helper generates HTML control based on the data type of specified property?

RadioButton() Helper method using the class to define the HTML elements. This is the loosely typed expansion method function which we can define as input type to select the (<input type="radio" >) element in razor view. We can declare the @Html.

Can we create custom HTML helper?

Creating HTML Helpers with Static MethodsThe easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a <label> .


2 Answers

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()

like image 160
hawkke Avatar answered Sep 22 '22 04:09

hawkke


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  );
}
like image 21
Tim M. Avatar answered Sep 24 '22 04:09

Tim M.