如何在mvc c#中单击后设置dropdonlist选定值

问题描述 投票:0回答:1

单击按钮后调用 Post 方法并且下拉选择将重置 该视图包含 在视图中:

@Html.DropDownList("Students", (IEnumerable<SelectListItem>)ViewBag.students, new { @class = "form-control" })
<input type="submit" value="Select" id="Submit" />

在控制器中我们通过函数设置虚拟数据

     public List<SelectListItem> DataList()
        {
            List<SelectListItem> students = new List<SelectListItem>() {
                new SelectListItem { Value = "1", Text = "Gyan" },
                new SelectListItem { Value = "2", Text = "Seeta" },
                new SelectListItem { Value= "3", Text = "Raam" },
                new SelectListItem { Value= "4", Text = "Shyam" },
                new SelectListItem { Value= "5", Text = "Ravi"}
            };
            return students;
        }

在控制器中,我们在索引操作中获取数据:

public ActionResult Index()
        {
            ViewBag.students = new SelectList(DataList(), "Value", "Text");
            return View();
        }

并通过Post Action获取数据

        [HttpPost]
        public ActionResult Index(Student student)
        {
            ViewBag.students = DataList();
            int selectedId = Convert.ToInt32(student.Id);
            string selectedText = ((List<SelectListItem>)ViewBag.students).FirstOrDefault(c => c.Value == selectedId.ToString())?.Text;
            return View();
        }
c# select model-view-controller view dropdown
1个回答
0
投票

我在页面顶部添加视图页面模型声明

@model WebApplication4.Models.Student

然后使用 'DropDownListFor' 而不是 'DropDownList'

<div class="col-md-4">
        <h2>Getting started</h2>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
        <div>
            @Html.DropDownListFor(model => model.Id, (IEnumerable<SelectListItem>)ViewBag.students, new { @class = "form-control" })
        </div>
        <input type="submit" value="Select" id="Submit" class="btn btn-default"  />
        }
    </div>

之后,当我们单击事件触发时,所选值不会更改。 :-)

© www.soinside.com 2019 - 2024. All rights reserved.