mic mic - 1 month ago 11
ASP.NET (C#) Question

anonymous list to DropDownListFor

I wrote this code in the controller

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


and in the view

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


but in the browser I get this result in dropdown

ResultPic

How can I fix this problem?

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");