Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC2 DropDownListFor

I am trying to learn MVC2, C# and Linq to Entities all in one project (yes, I am mad) and I am experiencing some problems with DropDownListFor and passing the SelectList to it.

This is the code in my controller:

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 am having troubles trying to get the DropDownListFor to take the MethodList in ViewData. When I try:

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

It errors out with the following message

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

I know why this is, as it is taking MethodList as a string, but I can't figure out how to get it to take the SelectList. If I do the following with a normal DropDownList:

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

It is quite happy with this.

Can anyone help?

like image 521
hermiod Avatar asked May 01 '10 12:05

hermiod


1 Answers

EDIT: So you are using Entity Framework, yes? In that case with the addition info you put in the comments, you would want 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 would be:

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

Your view code would be:

<%@ 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) %>
like image 175
Tejs Avatar answered Sep 28 '22 09:09

Tejs