Выпадающий список в ASP.NET MVC - PullRequest
0 голосов
/ 11 февраля 2019

Я хочу создать два раскрывающихся списка, но данные поступают в один раскрывающийся список, как показано ниже:

введите описание изображения здесь

идругой пустой

я хочу, чтобы B1 и B2 были в одном раскрывающемся списке

, а имя zahra в другом раскрывающемся списке

Этот код в контроллере:

// 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();
}

И это в виде

    <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>

Ответы [ 3 ]

0 голосов
/ 11 февраля 2019

Проблема в вашем втором цикле for-each, когда вы добавляете SelectListItem в первый список, который фактически предназначен для клиента.

Более того, упростите ваш метод Create GET следующим образом.Это уменьшит сложность.

// GET: Contracts/Create
[HtttpGet]
public ActionResult Create()
{
    var sections = _context.Sections.ToList();
    var customers = _context.Customers.ToList();

    ViewBag.SectionSelectList = new SelectList(sections,"Section_Id","Section_Name");
    ViewBag.CustomerSelectList = new SelectList(customers,"Customer_Id","Customer_Name");

    return View();
 }

Затем в представлении замените ваши @Html.DropDownListFor на следующие:

@Html.DropDownListFor(model => model.CustomerId, ViewBag.CustomerSelectList, "Select customers", new { @class = "form-control" })

@Html.DropDownListFor(model => model.SectionsId, ViewBag.SectionSelectList , "Select Sections", new { @class = "form-control" })
0 голосов
/ 11 февраля 2019

Попробуйте это:

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


       var listOfCustomers = new List<SelectListItem>();

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

        }

        ViewBag.Customers = listOfCustomers;

        var listOfSections = new List<SelectListItem>();

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

            }
        ViewBag.Sections = listOfSections;

            return View();
        }
0 голосов
/ 11 февраля 2019

Во 2-м цикле foreach вы добавляете в 1-й список вместо 2-го списка, названного list1.Корректированные данные, приведенные ниже:

    public ActionResult Create()
    {

        var Sections = _context.Sections.ToList();

        var Customers = _context.Customers.ToList();

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

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


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

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

        return View();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...