I originally created an editor template like this
@model MyModel
var items = // get items
@Html.DropDownListFor(m => m.Id, items, new { id = Html.IdFor(m => m) })
which was invoked by
@Html.EditorFor(m => m.SomeClass)
where SomeClass has an Id property. (The IdFor is one of my HTML helpers).
This would generate something like this
<select name="SomeClass.Id" id="SomeClass" />
Now I want to change the editor template into an HTML helper, so that my call looks like this
@Html.CustomEditorFor(m => m.SomeClass)
I’m changing this from a view to helper because its easier for reusability.
This is loosely what I have:
public static MvcHtmlString CustomEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
var idString = htmlHelper.IdFor(expression);
var propertyValue = expression.Compile()(htmlHelper.ViewData.Model);
var items = // get items
return htmlHelper.DropDownListFor(expression, items, new {id = idString});
}
However, when I call the editor, I get this HTML instead of what I want.
<select name="SomeClass" id="SomeClass" />
How can I modify the expression enough to allow it to “access” the Id property?
Try this: