views:

227

answers:

1

I have created a custom ViewModel and one of the fields is a SelectList/DropDownlist. I wanted to use EditorForModel to display the ViewModel. All the fields work except the SelectList. I have tried a few different things and nothing has come up. I saw on one post that EditorForModel was not "smart enough" to do a DropDownList and I was wondering if that is true. The EditorForModel is so much easier to use and less typing :)

Thanks!

UPDATE

I figured it out. What I ended up doing was using the UIHint("TemplateName") and in the EditorTemplates folder created a .ascx file that outputted was I expected.

A: 

In your viewmodel, you should have an IEnumerable<SelectListItem>

public IEnumerable<SelectListItem> Months { get; set; }

And in the aspx, you need to bind it as follows:

<%
    var htmlAttributes = new Dictionary<string, object> { { "data-autopostback", "true" } }; 
%>

<%:Html.DropDownList("Month", Model.Months, "-- All --", htmlAttributes)%>

You need to ensure that you populate the Months property before passing it to the view.

Let me know if you need the code to populate the Months property.

Rashmi Pandit
I think you missed my point. I wanted to try and use the EditorForModel(), which means I would not have to use the Html.DropDownList. That is what I'm trying to figure is possible.
Jamie R Rytlewski
@Rashmi Pandit if you have IEnumerable<SelectListItem> in the ViewModel how are you going to get the selected value back ? cuz on the form post you get a string[] with the selected keys for this Property
Omu
Omu, the parameter should be named Month in the method used by the controller to get the selected value. I've not tested it for multi-select drop downs though.
Rashmi Pandit