Rendering and Binding Drop Down Lists using ASP.NET MVC 3 EditorFor

Hi,

I wanted to render a drop down list on my EditorTemplates. I notice on the net allot of people creating ascx controls and using something like:

[UIHint("List")]

if you do not, you end up with an error:

error CS0305: Using the generic type ‘System.Collections.Generic.IEnumerable<T>’ requires 1 type arguments

However, this is not necessary in MVC 3, I am using Razor, so cshtml. I am sure it will work just as well in MVC2.

All you need to do is be explicit on the generics e.g.

In my cshtml file which is in the EditorTemplates, I have this:


Click me for ENUM lists

<div class="editor-field">
 @Html.DropDownList("CategoryId", new SelectList(ViewData["Categories"] as IEnumerable<PhotoRA.Web.Models.Category>, "CategoryId", "Name", Model.CategoryId))
 </div>

All I do is cast the ViewData with the as clause and use my generic type:

as IEnumerable<PhotoRA.Web.Models.Category>

So, no need for a ASCX file just for a dropdownlist!

The ViewModel in this case looks like this:

public class StoreManagerViewModel
{
 public Photo Photo { get; set; }
 public List<Category> Categories { get; set; }
 public List<Event> EventList { get; set; } 

}


Click me for ENUM lists

Advertisement

3 thoughts on “Rendering and Binding Drop Down Lists using ASP.NET MVC 3 EditorFor

  1. Nice Stuff.

    I believe SelectList is now able to take a Generic “List” without any sort of casting.

    List GradeList = new List();
    GradeList.Add(new Grade(“A”));
    GradeList.Add(new Grade(“B”));
    GradeList.Add(new Grade(“C”));
    GradeList.Add(new Grade(“D”));
    GradeList.Add(new Grade(“F”));

    viewModel.GradeList = new SelectList(GradeList, “Label”, “Label”, “A”);

    Post.cshtml

    @Html.DropDownListFor(model => model.Grade, Model.GradeList

    Thanks!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s