ASP.Net MVC2 DropDownListFor

I am trying to learn MVC2, C # and Linq for Entities in one project (yes, I'm crazy) and I am having some problems with DropDownListFor and passing SelectList to it.

This is my controller code:

public ActionResult Create() { var Methods = te.Methods.Select(a => a); List<SelectListItem> MethodList = new List<SelectListItem>(); foreach (Method me in Methods) { SelectListItem sli=new SelectListItem(); sli.Text = me.Description; sli.Value = me.method_id.ToString(); MethodList.Add(sli); } ViewData["MethodList"] = MethodList.AsEnumerable(); Talkback tb = new Talkback(); return View(tb); } 

and I'm having problems trying to get DropDownListFor to take a MethodList in ViewData . When I try:

 <%:Html.DropDownListFor(model => model.method_id,new SelectList("MethodList","method_id","Description",Model.method_id)) %> 

It displays a message with the following message

 DataBinding: 'System.Char' does not contain a property with the name 'method_id'. 

I know why this is so, since it takes a MethodList as a string, but I cannot figure out how to get it to take a SelectList . If I do the following with a normal DropDownList :

 <%: Html.DropDownList("MethodList") %> 

It is very pleased with this.

Can anyone help?

+6
c # asp.net-mvc-2
source share
1 answer

EDIT . So you are using Entity Framework, yes? In this case, with the addition of the information you added in the comments, you would like to do something like this:

 public ActionResult Create() { var viewModel = new CreateViewModel(); // Strongly Typed View using(Entities dataModel = new Entities()) // 'te' I assume is your data model { viewModel.Methods = dataModel.Methods.Select(x => new SelectListItem() { Text = x.Description, Value = x.method_id.ToString() }); } return View(viewModel); } 

Your strongly typed view model will be:

 public class CreateViewModel { public string SelectedMethod { get; set; } public IEnumerable<SelectListItem> Methods { get; set; } } 

Your view code:

 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<CreateViewModel>" %> <%-- Note the Generic Type Argument to View Page! --%> <%: Html.DropDownListFor(m => m.SelectedMethod, Model.Methods) %> 
+8
source share

All Articles