Set selected value in dropdown list

2019-07-08 04:46发布

How do I set the selected value on a drop down list? Here is what I have so far:

@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条回答
姐就是有狂的资本
2楼-- · 2019-07-08 05:20

I would recommend you to avoid using ViewBag/ViewData/ Weekly typed code. Use strongly typed code and it makes it more readable. Do not use the Magic strings/ Magic variables. I would add a collection property to your ViewModel to hold the SelectList items and another property to hold the selected item value.

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

  //Other Properties
}

and in your Get action, If you want to set some Item as selected,

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

Now in the View, use the Html.DropDownListFor helper method

@Html.DropDownListFor(x=>x.SelectedSpeciality,Model.SpecialtyItems,"select one ")
查看更多
对你真心纯属浪费
3楼-- · 2019-07-08 05:40

Use the selected property of the SelectListItem class:

selList.Selected = true;
查看更多
登录 后发表回答