使用SelectListItem设置DropDownList的选定值

时间:2019-03-31 12:51:32

标签: c# jquery asp.net-mvc model-view-controller

尽管已经问过几次这个问题,但我仍在努力寻找解决问题的方法

我有一个下拉菜单,我想在检索数据时绑定选定的值。 这是我的控制器

studentList = db.Students
                    .Select(x => new SelectListItem
                    {
                        Value = x.StudentId.ToString(),
                        Text = x.StudentNo + " - " + x.StudentNameEn
                    }).ToList();
                ViewData["studentList"] = studentList;

这是我的看法

 @Html.DropDownList("StudentNo", ViewData["studentList"] as List<SelectListItem>, "---Please Select---", new { @class = "form-control selectpicker", id = "studentIdDrp" })

我尝试过的事情

  1. 我尝试使用jquery绑定值

    $("#studentIdDrp").val('@Model.AppointmentViewModel.FK_StudentId');
    
  2. 我尝试从控制器设置所选属性为真

    foreach(var item in studentList)
                {
                    if (item.Value == appoinmnetRec.FK_StudentId.ToString())
                    {
                        item.Selected = true;
                    }
                }
    

以上方法均无效。请帮助,在此先感谢

1 个答案:

答案 0 :(得分:1)

我试图重现您的问题。在我的机器上,选定的值有效。

控制器:

None

查看:Student.cshtml

namespace WebApplication2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";
            var studentList = new List<SelectListItem>()
            {
                new SelectListItem {Text = "ABC", Value = "1"},
                new SelectListItem {Text = "CDE", Value = "2"},
            };
            ViewData["studentList"] = studentList;
            return View();
        }

        public ActionResult Student()
        {
            var studentList = new List<SelectListItem>()
            {
                new SelectListItem {Text = "Peter Cech", Value = "S001"},
                new SelectListItem {Text = "Leo Messi", Value = "S002"},
            };
            ViewData["studentList"] = studentList;
            AppointmentViewModel model = new AppointmentViewModel();
            model.FK_StudentId = "S001";

            return View(model);
        }
    }

    public class AppointmentViewModel
    {
        public string FK_StudentId { get; set; }
    }
}