drop-down list in MVC

Refresh

February 2019

Views

9 time

0

i Crete two drop-down list , but the data come on one drop-down list like this picture :

enter image description here

and the other one is empty

i want the B1 and B2 in one drop-down list

and name zahra in other drop-down list

This code in the controller :

 // GET: Contracts/Create
    public ActionResult Create()
    {

        var Sections = _context.Sections.ToList();

        var Customers = _context.Customers.ToList();

        List<SelectListItem> list = new List<SelectListItem>();

        foreach (var item in Customers)
        {
            list.Add(new SelectListItem { Text = item.Customer_Name, Value = item.Customer_Id.ToString() });

            ViewBag.Customers = list;
        }


        List<SelectListItem> list1 = new List<SelectListItem>();

            foreach (var item in Sections)
            {
                list.Add(new SelectListItem { Text = item.Section_Name, Value = item.Section_Id.ToString() });

                ViewBag.Sections = list1;
            }


            return View();
        }

And this is in the View

    <div class="form-group">
        @Html.LabelFor(model => model.CustomerId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CustomerId, (IEnumerable<SelectListItem>)ViewBag.Customers, "Select customers", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.CustomerId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.SectionsId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.SectionsId, (IEnumerable<SelectListItem>)ViewBag.Sections, "Select Sections", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.SectionsId, "", new { @class = "text-danger" })
        </div>
    </div>

1 answers

0

Во 2-м цикле Еогеасп вы добавляете в 1-ом списке вместо 2 списка с именем, как list1.

    public ActionResult Create()
    {

        var Sections = _context.Sections.ToList();

        var Customers = _context.Customers.ToList();

        List<SelectListItem> list = new List<SelectListItem>();

        foreach (var item in Customers)
        {
            list.Add(new SelectListItem { Text = item.Customer_Name, Value = item.Customer_Id.ToString() });

            ViewBag.Customers = list;
        }


        List<SelectListItem> list1 = new List<SelectListItem>();

            foreach (var item in Sections)
            {
                list1.Add(new SelectListItem { Text = item.Section_Name, Value = item.Section_Id.ToString() });

                ViewBag.Sections = list1;
            }


            return View();
        }