c# - 列出外键 MVC 的表值

标签 c# asp.net-mvc

这是我正在上的课:

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>

这是我的 Controller :

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>'

我想要做的就是在下拉列表中显示计划类(来自数据库)的数据,这是我正在处理的类的外键。

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

最佳答案

这里有几处错误:

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

您直接在您的 View 中使用您的业务模型,这有点不对。因为,在你的特定情况下,你必须初始化你的列表,所以你必须有所有计划的集合可供选择。这不是您的业务模型的一部分。而不是 CS.Models.appointment您必须使用一个 View 模型,它将包含您填写的所有属性以发布您的 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);
}

并且不要忘记更新您的 View 以使用 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>

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

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");
}

关于c# - 列出外键 MVC 的表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34137600/

相关文章:

c# - ASP .Net MapRequestHandler 慢

javascript - 使用 JSON 将分类数据从 SQL 导入到 C3.js

asp.net-mvc - 按 Controller 或模型限制访问?

asp.net-mvc - ASP.NET MVC 框架中的 MVVM 和 ModelBinders

c# - MonoTouch 确定性处理单元

c# - 使用 ajax 调用 Web 服务

c# - WIF 的 SessionAuthenticationModule 始终为空。为什么?

asp.net-mvc - 没有查询字符串的 RedirectToAction MVC

asp.net-mvc - 当参数为模型时,ASP.NET MVC 发布文件模型绑定(bind)

c# - 将数组发布到 Azure Function HTTP 触发器返回 500 状态代码