In a custom editor template, how do I access the field name I should use for the edit control? [duplicate]

StackOverflow https://stackoverflow.com/questions/9293253

Вопрос

Possible Duplicate:
How to get model's field name in custom editor template

When outputting an edit control for a special type of entity, for example, let’s say a color or something:

@Html.EditorFor(product => product.Color)

I want this to output a drop-down list, so I tried to create a custom editor template that shall render such a drop-down. Here is what my template looks like so far:

@model MyProject.Models.Color
@using (var db = new MyProject.Models.DbContext())
{
    @Html.DropDownList(???,
        new SelectList(db.Colors, "Id", "Name", Model))
}

What do I have to put instead of the ??? — the parameter that specifies the HTML name attribute for the drop-down?


(For obvious reasons, it’s not just "Color". Consider several invocations of the same edit template for different fields of the same type, e.g.:

@Html.EditorFor(product => product.InnerColor)
@Html.EditorFor(product => product.OuterColor)

Clearly, this needs to generate drop-downs with different names.)

Это было полезно?

Решение

The drop-down list already receives the correct field name all by itself. Anything you pass into the name parameter gets concatenated onto the field name, preventing it from being recognised.

The correct solution is to pass the empty string:

@Html.DropDownList("", new SelectList(...))

Другие советы

An answer to this question suggests to use

ViewData.TemplateInfo.HtmlFieldPrefix

So the full code will be somthing like

@model MyProject.Models.Color
@using (var db = new MyProject.Models.DbContext())
{
    @Html.DropDownList(ViewData.TemplateInfo.HtmlFieldPrefix + "_Color",
        new SelectList(db.Colors, "Id", "Name", Model))
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top