Trouble getting DropDownListFor to work on EditorFor in MVC3
Asked Answered
L

1

10

I've got a pretty simple problem that has a solution I'm not able to find.

Given the following model:

public class InfoViewModel
{
    public SelectList States { get; set; }

    [DisplayName("State")]
    public string State { get; set; }
}

The following works fine in my view:

@Html.DropDownListFor(m => m.State, Model.States)

However, if I try to pull this into an editor template (named "SelectList"), such as:

@model System.String
@Html.DropDownListFor(m => m, ViewData["selectList"])

And then use EditorFor to build the dropdown list:

@Html.EditorFor(m => m.State, "SelectList", new { selectList = Model.States })

It fails with the following error:

'System.Web.Mvc.HtmlHelper<string>' does not contain a definition for 
'DropDownListFor' and the best extension method overload 
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>
(System.Web.Mvc.HtmlHelper<TModel>, 
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, 
System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' 
has some invalid arguments

I'm having a hard time understanding the difference between these two. I've tried various workarounds to troubleshoot, and either get the same error, or something else.

Thanks in advance.

Lefthand answered 12/6, 2011 at 1:48 Comment(1)
thanks...,your quetion are usefull for as my answer///Sweatbox
W
15

There is no such overload:

@Html.DropDownListFor(m => m, ViewData["selectList"])

The second parameter of the DropDownListFor helper musty be a SelectList. So:

@Html.DropDownListFor(m => m, (SelectList)ViewData["selectList"])
Warrin answered 12/6, 2011 at 8:7 Comment(1)
Thanks, Darin, that was exactly it. I should have realized that.Lefthand

© 2022 - 2024 — McMap. All rights reserved.