0

Can anyone help me to figure out how do I do this when v.ID is a integer property in my model?

ViewBag.VendorID = new SelectList(db.Vendors.Select(v => new SelectListItem
{
    Value = v.ID,
    Text = string.Format("{0} {1} {2}", v.Title, v.Firstname, v.Secondname)
}), "Text", "Value");

return View();

I am trying to combine several properties from my model into the text of a dropdown list. This shows a compile time error, and yet if I change it to

ViewBag.VendorID = new SelectList(db.Vendors.Select(v => new SelectListItem
{
    Value = v.ID.ToString(),
    Text = string.Format("{0} {1} {2}", v.Title, v.Firstname, v.Secondname)
}), "Text", "Value");

then this line from my view

@Html.DropDownList("VendorID", (SelectList)ViewBag.VendorID)

raises a run-time error:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

Any thoughts on how I can resolve this apparently simple task

Thanks all.

Jason.

1 Answer 1

3

You can't use string.Format directly in Linq-to-SQL. You need to enumerate the list first:

ViewBag.VendorID = db.Vendors.ToList().Select(v => new SelectListItem
{
    Value = v.ID,
    Text = string.Format("{0} {1} {2}", v.Title, v.Firstname, v.Secondname)
});

return View();

Note the addition of .ToList() above. I've also removed the SelectList constructor, as DropDownList accepts an IEnumerable<SelectListItem> already which you are generating yourself.

Sign up to request clarification or add additional context in comments.

4 Comments

This worked with the SelectList constructor. However, once removed a exception is raised: Unable to cast object of type 'WhereSelectListIterator`2[Model.Vendor,System.Web.Mvc.SelectListItem]' to type 'System.Web.Mvc.SelectList'. Any thoughts or should I just leave the constructor in place?
Simply remove the cast to SelectList in your View: @Html.DropDownList("VendorID") should try to bind it to the VendorID ViewBag property
Perfect. Many thanks. Can you suggest any useful resources (apart from stackoverflow) to read up on this stuff in detail. Finding the answer to this question seemed much more difficult that it should have been and yet the articles and pluralsight stuff I read so far didn't touch on it at all.
Don't think I'll ever say this again, but the ASP.net site is a great resource for MVC tutorials. Specifically this: DropDownList helper tutorial

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.