8

I'm trying to populate a @Html.DropDownList with a List using MVC and Razor. Bellow is my code for the controller. So I need to pick the list out of my ViewBag and fill the dropdownlist.

public ActionResult Register()
    {
        sparklingEntities context = new sparklingEntities();
        var query = (from discs in context.Disciplines
                     select discs).ToList();
        List<string> listOfDiscs = new List<string>();
        foreach (var item in query)
        {
            listOfDiscs.Add(item.Discipline);
        }
        ViewBag.ListOfDisciplines = listOfDiscs;
        return View();
    }

Thanks for the help.

3 Answers 3

13

If this is in an Editor for your model property:

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

Comments

1
//Increase performance by Eliminating foreach loop!
public ActionResult Register()
{
    sparklingEntities context = new sparklingEntities();
    var query = (from discs in context.Disciplines
                 select discs.Discipline); // change this line as discs.Discipline
    ViewBag.ListOfDisciplines = listOfDiscs;
    return View();
}

Comments

0

value is not getting saves in the database..please see where i am getting mistake...

    public ActionResult Role(Role_Master_Table t)
    {
        FTSdatabaseEntities dc = new FTSdatabaseEntities();
        {

            //ViewBag.Status_Description = new SelectList(dc.Status_Master_Table, "StatusId", "Status_Description", "Remarks");
            var query = (from Status_Description in dc.Status_Master_Table
                         select Status_Description).ToList();
            List<string> listOfDiscs = new List<string>();
            foreach (var item in query)
            {
                listOfDiscs.Add(t.Status);
                dc.Role_Master_Table.Add(t);
                dc.SaveChanges();

            }
            ViewBag.Status_Description = listOfDiscs;


            return View();
        }

Comments

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.