How can I get the property name in my MVC3 custom Editor Template
You can get the property name in the editor template via
@{
string name = ViewData.ModelMetadata.PropertyName;
}
For future reference (old question), I found this: System.Web.Mvc.Html.NameExtensions.
Using those, you can do something like
<input type=text" name="@Html.NameFor(m => m.MyProperty)">
And you'll get
<input type=text" name="MyProperty">
There are several other related helpers in this extension class. This method does more than just get the property name, though. For example, you could use m.MyProperty.MySubProperty and you'd get a valid HTML name for posting.
I found the answer in a book I have here. Actually, it got me close, but I then could google the rest based on what I found.
Here is what I needed to add to my editor template.
@{var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;}
<select id="@fieldName" name="@fieldName">
How about the following template:
@model ItemEnumerations.ItemType
@{
var values =
from value in Enum.GetValues(typeof(ItemType)).Cast<ItemType>()
select new { ID = (int)value, Name = value.ToString() };
var list = new SelectList(values , "ID", "Name", (int)Model);
}
@Html.DropDownList("", list)
This way you don't need to manually render <select>
and <option>
tags and you are reusing the existing DropDownList
helper.