3

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

@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;
       }
4

2 回答 2

2

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

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

  //Other Properties
}

在您的 Get 操作中,如果您想将某些项目设置为选中状态,

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 ")
于 2012-08-01T19:03:09.853 回答
0

使用 SelectListItem 类的 selected 属性:

selList.Selected = true;
于 2012-08-01T18:52:31.027 回答