如何在下拉列表中设置所选值?这是我到目前为止的内容:

@model Web.Models.PostGraduateModels.PlannedSpecialty

@Html.DropDownList("PlannedSpecialtyID")

//controller
        [HttpGet]
        public PartialViewResult PlannedSpecialty()
        {

            // Get Planned Specialty ID
            var pgtservice = new PgtService();
            PostGraduateModels.PlannedSpecialty plannedSpecialty = pgtservice.GetPlannedSpecialtyId();


           // Get Data for Planned Specialty DropDown List from SpecialtyLookup
            var pgtServ = new PgtService();
            var items = pgtServ.GetPlannedSpecialtyDropDownItems();
            ViewBag.PlannedSpecialtyId = items;

            return PartialView(plannedSpecialty);


        }

// service
        public IEnumerable<SelectListItem> GetPlannedSpecialtyDropDownItems ()
        {
            using (var db = Step3Provider.CreateInstance())
            {
                var specialtyList = db.GetPlannedSpecialtyDdlItems();

                return specialtyList;

            }

        }

// data access
        public IEnumerable<SelectListItem> GetPlannedSpecialtyDdlItems()
       {

            IEnumerable<Specialty> specialties = this._context.Specialties().GetAll();
            var selList = new List<SelectListItem>();

            foreach (var item in specialties)
            {
                var tempps = new SelectListItem()
                    {
                        Text = item.Description,
                        Value  = item.Id.ToString()
                    };
                selList.Add(tempps);
            }


            return selList;
       }

最佳答案

我建议您避免使用ViewBag / ViewData /每周键入的代码。使用强类型代码,使代码更具可读性。不要使用魔术字符串/魔术变量。我会向您的ViewModel添加一个collection属性来保存SelectList项,并添加另一个属性来保存所选项的值。

public class PlannedSpecialty
{
   public IEnumerable<SelectListItem> SpecialtyItems { set;get;}
   public int SelectedSpeciality { set;get;}

  //Other Properties
}


在“获取操作”中,如果您想将某些项目设置为选中状态,

public PartialViewResult PlannedSpecialty()
{
    var pgtServ = new PgtService();
    var vm=new PlannedSpecialty();
    vm.SpecialtyItems = pgtServ.GetPlannedSpecialtyDropDownItems();

   //just hard coding for demo. you may get the value from some source.
    vm.SelectedSpeciality=25;//  here you are setting the selected value.
   return View(vm);
}


现在,在视图中,使用Html.DropDownListFor辅助方法

@Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")

关于c# - 在下拉列表中设置所选值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11765573/

10-11 04:44