发布数据时,填充selectlistiitem出错

本文关键字:填充 selectlistiitem 出错 布数据 数据 | 更新日期: 2023-09-27 18:08:41

我正在与ASP合作。. NET MVC 4,我试图填充从我的数据库下拉列表这样做:

My models:

public class AppointmentViewModel
{
    public string DisplayDate { get; set; }
    public DateTime BirthDate { get; set; }

    public MedecinViewModel Medecin { get; set; }
    public SuggestionViewModel Suggestion { get; set; }
}
public class MedecinViewModel
{
    public int MedecinId { get; set; }
    public String MedecinNom { get; set; }
}

我的下拉列表:

<div class="editor-field">
                 @Html.DropDownListFor(a => a.Medecin.MedecinId, (SelectList)ViewBag.Medecins, "Choisissez un médecin")
            </div>

My controller:

ViewBag.Medecins = new SelectList(context.DBMedecins, "MedecinId", "FullName");

似乎在做我的post动作之后,出现了错误,我得到以下错误消息:

键为'Medecin '的ViewData项。MedecinId'的类型是'System '。Int32',但必须是类型'IEnumerable'?

那有什么不对吗?

EDIT: My GET and POST Controllers

    [HttpGet]
    public ActionResult ConfirmAppointment(string interval)
    {
        context = new SchedulingDataClassesDataContext();
        ViewBag.Medecins = new SelectList(context.DBMedecins, "MedecinId", "FullName");
        return View();
    }
    [HttpPost]
    public ActionResult ConfirmAppointment(AppointmentViewModel avm)
    {
        context = new SchedulingDataClassesDataContext();
        if (ModelState.IsValid)
        {
            //logical code
        }
        return View(avm);
    }

发布数据时,填充selectlistiitem出错

您需要在ViewBag中再次填充SelectList,因为在post action之后它再次呈现视图,但Viewbag.Medecins未在post action中设置,因此它变为空,因为ViewBag范围仅从动作到视图,之后它再次变为空:

[HttpPost]
    public ActionResult ConfirmAppointment(AppointmentViewModel avm)
    {
        context = new SchedulingDataClassesDataContext();
        if (ModelState.IsValid)
        {
            //logical code
        }
        ViewBag.Medecins = new SelectList(context.DBMedecins, "MedecinId", "FullName");
        return View(avm);
    }