c# - 如何根据 SQL 数据库中的 Id 填充下拉列表
问题描述
我正在尝试在我的一个 CRUD 屏幕中创建一个下拉列表,该下拉列表基于我的程序中的不同模型。现在它根据 ID 输入值,但我希望它能够在下拉列表中填充教师的姓名。
我使用选择列表尝试了一些不同的方法,但似乎没有用。
这是我的模型:
[Table("Section")]
public class Section
{
[Key]
public int Id { get; set; }
[DisplayName("Section")]
public int? section { get; set; }
public Nullable <int> instructor_id { get; set; }
public int location_id { get; set; }
public int modality_id { get; set; }
public int DOW_id { get; set; }
public int course_id { get; set; }
public virtual DOW DOW { get; set; }
public virtual Instructor Instructor { get; set; }
public virtual Location Location { get; set; }
public virtual Modality Modality { get; set; }
public virtual Course Course { get; set; }
这是我的控制器:
// GET: Sections/Create
public ActionResult Create()
{
return View();
}
// POST: Sections/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,section,startTime,endTime,startDate,endDate,isTap,isActive,instructor_id,location_id,modality_id,DOW_id,course_id")] Section section)
{
if (ModelState.IsValid)
{
db.Sections.Add(section);
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.instruct = new SelectList(db.Instructors, "Id", "lname", section.instructor_id);
return View(section);
}
这是我的观点
<div class="form-group">
@Html.LabelFor(model => model.instructor_id, "instructor_id" , htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.instructor_id, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.instructor_id, "", new { @class = "text-danger" })
</div>
</div>
解决方案
取自约翰彼得斯的答案,请看一下
创建一个数据层来检索您想要的列表。然后使用 EF 获取所有状态。
//assuming you have a table of states..
var states = db.States();
状态表应该是唯一的状态列表。
var selectList = new List<SelectListItem>();
foreach(var thing in states){
//if you got everything, thus the ID field for the value...
selectList.Add(new SelectListItem {Text =thing.State, Selected = false, Value = thing.ID);
}
确保在您的 Viewmodel 类中 selectlist 是一个公共属性......并设置为您在上面所做的。您还需要为视图选择回发提供一个字符串。
StatesSelectList = selectList;
public IEnumerable<SelectListItem> StatesSelectList {get;set;}
public string SelectedState {get;set;}
在您看来,请执行以下操作:
@Html.DropDownListFor(p => Model.SelectedState, Model.StatesSelectList)
推荐阅读
- c++ - 设置服务访问规则
- git - ReactJS:构建基本 git GUI 的 npm 包?
- linux - 从jenkins jmeter.log进行午餐测试时访问jmeter.log文件(权限被拒绝)java.io.FileNotFoundException:错误
- cookies - AppSync:如何设置标头作为响应?
- javascript - 在 jquery 的帮助下选择下拉菜单的值
- javascript - 在数组reactjs中查找元素
- java - 如何使用opencv确定是否检测到对象
- jquery - jQuery获取空输入
- php - yii2 - 前端到后端和后端到前端控制器配置文件 + .htaccess - 完全配置
- angularjs - 如何将多个值从 Asp.Net WebApi 发送到 Angularjs 控制器?