mic mic - 26 days ago 21
ASP.NET (C#) Question

anonymous list to DropDownListFor code fist

i write this code in controller

public ActionResult Create()
{
ViewBag.CustomerList = new SelectList(db.Customers.Select(m => new { Id = m.Id, m.Name, m.LastName }));

return View();
}


and in view

@Html.DropDownListFor(model => model.Customer.Id, (SelectList)ViewBag.CustomerList, "", new { @class = "form-control" })


but in browser i get this result in dropdown

ResultPic

how i can fix this problem ?

thank you

Answer

change the controller code to this

        ViewBag.CustomerList = new SelectList(db.Customers.Select(m => new SelectListItem { Value = m.Id.ToString(), Text = m.Name + " " + m.LastName }), "Value", "Text");
Comments