1

I know that there are plenty of similar questions but I couldn't get it working ... I want to populate dropdown list from entity framework entity. I have following entity class:

namespace Accounting.Entity
{
    [Table("Cities", Schema = "np")]
    public class Cities
    {
        [Key]
        [XmlElement("Ref")]
        public System.Guid Ref { get; set; }
        [XmlElement("Description")]
        public string Description { get; set; }

    }
}

Controller:

public class OrderController : Controller
{

    public ActionResult PopulateCitiesDD()
    {

        var list = _repository.All<Cities>().ToList();
        ViewBag.MyCities = new SelectList(list, "Ref", "Description", 0);
        return View();
    }
}

What should I use in the view to populate dropdown?

2
  • 1
    DropDownListFor is fine Commented Oct 2, 2015 at 16:00
  • what is the first param for DropDownListFor? Commented Oct 2, 2015 at 16:06

1 Answer 1

1

Based on the controller/action code you posted, you could create a dropdown list in your view like this:

@Html.DropDownList("city", (SelectList)ViewBag.MyCities)
Sign up to request clarification or add additional context in comments.

3 Comments

Message=There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'city'.
Hmm. Just to be sure: you're setting ViewBag.MyCities in the controller?
@sidux, You would only ever get that message if ViewBag.MyCities is null (possibly because in a POST method you return the view but have not reassigned ViewBag.MyCities as you did in the GET method)

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.