Я пытаюсь создать раскрывающийся список на одном из моих экранов CRUD, основанный на другой модели в моей программе. Прямо сейчас он вводит значения на основе идентификатора, но я хочу, чтобы он мог заполнять имена инструкторов в раскрывающемся списке.
Я пробовал несколько разных вещей, используя список выбора, но, похоже, это не сработало.
Это моя модель:
[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 этот список выбора является общедоступным свойством... и установите то, что вы сделали выше. Вам также необходимо указать строку для обратного сообщения о выборе вида.
StatesSelectList = selectList;
public IEnumerable<SelectListItem> StatesSelectList {get;set;}
public string SelectedState {get;set;}
На ваш взгляд, сделайте так:
@Html.DropDownListFor(p => Model.SelectedState, Model.StatesSelectList)
Вам нужно изменить метод Get в контроллере следующим образом:
// GET: Sections/Create
public ActionResult Create()
{
ViewBag.Instructors = db.Instructors.ToList();
return View();
}
Ваш HTML должен быть изменен следующим образом:
<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.DropDownListFor(model => model.instructor_id, new SelectList(ViewBag.Instructors, "Id", "Name"), new { @class = "form-control" } )
@Html.ValidationMessageFor(model => model.instructor_id, "", new { @class = "text-danger" })
</div>
</div>
Убедитесь, что имена полей указаны правильно.
пожалуйста, есть ссылка stackoverflow.com/a/26663526/7262120 Джона Питерса