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?
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) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With