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:
<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; } }
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!
Here is how to render lists from enums.
https://romikoderbynew.com/2012/02/23/asp-net-mvc-rendering-enum-dropdownlists-radio-buttons-and-listboxes/