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?
The MaxLength for TextBoxes is set using the HTML MaxLength attribute using the HtmlAttributes parameter in Html. TextBox and Html. TextBoxFor helper functions.
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.
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> .
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()
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With