gpt4 book ai didi

c# - 在下拉列表中设置选定值

转载 作者:行者123 更新时间:2023-11-30 17:10:49 25 4
gpt4 key购买 nike

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

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

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com