首页 > 解决方案 > 如何根据 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>

标签: c#asp.net-mvccrudviewbag

解决方案


取自约翰彼得斯的答案,请看一下

创建一个数据层来检索您想要的列表。然后使用 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)

推荐阅读