Friday 15 November 2013

Using Editor Template for Rendering DropDownList

Below is an example of how to have a dropdownlist when editing a model that has an integer type property used for foreign key property. I.e.; I have a model that has this property:
int ItemId { get; set; }
Then I want every time an instance of this model type is being edited, the field is shown as a dropdownlist. To do this, inside 'EditorTemplates' folder under the global 'Views\Shared' or a view's specific folder, I create a partial view named 'Item.cshtml' like below:
@Html.DropDownListFor(model => ViewData.TemplateInfo.FormattedModelValue, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = (Model != null) && (option.ItemId == (int)ViewData.TemplateInfo.FormattedModelValue)
            }), "Please select")
Note that, I use ViewData.TemplateInfo.FormattedModelValue to get the value. I could also write like this by declaring the model to use:
@model int

@Html.DropDownListFor(model => model, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = option.ItemId == Model
            }), "Please select")
Then to render the custom template on my edit view page, I do:
@Html.EditorFor(model => model.ItemId, "Item")

For more details about Editor Template or Display Template, you could see my previous post.

3 comments:

Anonymous said...

Hi, in the below code :

@model int
 
@Html.DropDownListFor(model => model, ((IEnumerable)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name,
                Value = option.ItemId.ToString(),
                Selected = option.ItemId == Model
            }), "Please select")

what is the Model ? in fact ((IEnumerable)

Anonymous said...

@model int
 
@Html.DropDownListFor(model => model, ((IEnumerable)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name,
                Value = option.ItemId.ToString(),
                Selected = option.ItemId == Model
            }), "Please select")


What is Model in (IEnumerable)?

rical said...

hi,

The first '@model' on top is to declare a model/object passed to a view or template along with its type. Then after that, we can use 'Model' (capital M) to refer to the model/object instance.