在下拉列表中设置选定的值

时间:2012-08-01 18:47:28

标签: c# asp.net-mvc-3 razor

如何在下拉列表中设置所选值?以下是我到目前为止的情况:

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

2 个答案:

答案 0 :(得分:2)

我建议您避免使用ViewBag / ViewData / Weekly类型的代码。使用强类型代码,使其更具可读性。不要使用Magic strings / Magic变量。我会向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 ")

答案 1 :(得分:0)

使用SelectListItem类的selected属性:

selList.Selected = true;