列出外键MVC的表值

本文关键字:MVC | 更新日期: 2023-09-27 18:25:56

这是我正在处理的类:

public class appointment
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int appointment_id { get; set; }
    [DataType(DataType.MultilineText)]
    public string appointment_description { get; set; }
    public int student_id { get; set; }
    public virtual student student { get; set; }
    public int sched_id { get; set; }
    public virtual sched schedule { get; set; }
}

正如你所看到的,我的一个外键是"时间表"。

这是我的时间表

public class sched
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int sched_id { get; set; }
        public string sched_day { get; set; }
        public TimeSpan sched_stime { get; set; }
        public TimeSpan sched_etime { get; set; }
        public int faculty_id { get; set; }
        public virtual faculty faculty { get; set; }
    }

我在创建时在MVC 5 CRUD中生成了这个,这是我认为的代码:

 <div class="col-md-10">
                @Html.DropDownList("sched_id", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.sched_id, "", new { @class = "text-danger" })
            </div>

这是我的控制器:

public ActionResult Book()
{
    return View();
}
[HttpPost]
public ActionResult Book(CS.Models.appointment appoint)
{
    if(ModelState.IsValid)
    {
        db.appointments.Add(appoint);
        db.SaveChanges();
    }
    return RedirectToAction("Booked", "Home");
}

但是出现了一个错误:

There is no ViewData item of type 'IEnumerable<SelectListItem>'

我想做的就是在dropdownlist中显示sched类(来自数据库)的数据,该类是我正在处理的类的外键。

有什么办法我能做到吗?我是MVC的新手。

列出外键MVC的表值

这里有几个错误:

首先-@Html.DropDownList("sched_id", null,这行代码。如果我理解正确的话,当你构建时间表的选择列表时,你必须提供你想要构建DropDownList的项目列表,而不是null。这是错误中提到的IEnumerable<SelectListItem>,不能为空。这就引出了第二个问题。

你直接在你的视野中使用你的商业模式,这有点不对。因为,在您的特定情况下,您必须初始化您的列表,因此您必须拥有可供选择的所有计划的集合。这不是你商业模式的一部分。您必须使用视图模型来代替CS.Models.appointment,该视图模型将包含您为发布appointment而填充的所有属性和两个附加成员:

IEnumerable<SelectListItem> ScheduleSelectListItems { get; set; };
int SelectedScheduleId { get; set; }

填充获取操作中将包含的SelectListItems的列表。类似这样的东西:

public class AppointmentViewModel
{
    public int appointment_id { get; set; }
    public string appointment_description { get; set; }    
    public StudentViewModel student { get; set; }
    public IEnumerable<SelectListItem> ScheduleSelectListItems { get; set; };
    public int SelectedScheduleId { get; set; }
}

public ActionResult Book()
{
    var items = db.schedules.ToList().Select(sched => new SelectListItem { Text = string.Format("{0} - {1}", sched.sched_stime, sched.sched_etime), Value = sched.Id });
    var model = new AppointmentViewModel { ScheduleSelectListItems = items };
    return View(model);
}

不要忘记更新您的视图,将AppointmentViewModel用作@model

<div class="col-md-10">
@Html.DropDownList("SelectedScheduleId", Model.ScheduleSelectListItems, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.SelectedScheduleId, "", new { @class = "text-danger" })
</div>

这就引出了第三个问题。由于您不使用任何视图模型,因此没有任何映射(将所有字段从视图模型复制到将保存到数据库的实际业务模型)。为了简化任务并避免目前为此目的使用AutoMapper等外部工具,您可以手动进行映射。例如,在一些外部类中,使控制器操作代码尽可能干净。

public static class Extensions
{
    public static appointment ToAppointment(this AppointmentViewModel appointmentViewModel)
    {
        var result = new appointment
        {
             appointment_id = appointmentViewModel.appointment_id;
             // Copy all other properties here
             ...
        };
        return result;        
    }
}
[HttpPost]
public ActionResult Book(AppointmentViewModel appoint)
{
    if(ModelState.IsValid)
    {
        // Map you view model to the model
        var appointment = appoint.ToAppointment();
        // Get you selected schedul from the database using either foreighn key either navigation property
        var schedule = db.schedules.FirstOrDefault(sched => sched.Id == appoint.SelectedScheduleId);
        appointment.schedule = schedule;
        db.appointments.Add(appointment);
        db.SaveChanges();
    }
    return RedirectToAction("Booked", "Home");
}
相关文章:
  • 没有找到相关文章