: '具有键 'PatientAppointmentID' 的 ViewData 项是 'System.Int32' 类型,但必须是 'IEnumerable<SelectListItem>' 类型。

: 'The ViewData item that has the key 'PatientAppointmentID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.'

我有一个来源,其中有一个下拉列表

 @Html.DropDownListFor(m => m.PatientAppointmentID, ViewBag.AppointmentDate as List<SelectListItem>," - Select Appointment Date -",new { @class = "form-control" })

它的控制器方法是:

public ActionResult Create(int? Patient_id)
{
    CreateBillViewModel model = new CreateBillViewModel();
    if (Patient_id != null)
    {
        List<SelectListItem> AppointmentDates = (from p in db.tblPatientAppointments
                                                 where p.patient_id == Patient_id
                                                 select new SelectListItem
                                                 {
                                                     Text = p.AppointmentDate,
                                                     Value = p.ID.ToString()
                                                 }).ToList();
        ViewBag.AppointmentDate = AppointmentDates;
    }
    return View(model);
}

它正在正确填充下拉列表中的值,但是当我填写表单和下拉列表中的 select 值时,出现以下错误:

System.InvalidOperationException: 'The ViewData item that has the key 'PatientAppointmentID' is of type 'System.Int32' but must be of type 'IEnumerable'.'

进一步提交表单,值存储在如下所示的会话中,我还希望 url 中的下拉列表和患者 ID 保留我想在会话中添加的更多值

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string nameValueInsert, string nameValueSubmit, CreateBillViewModel model)
{
    var button = nameValueInsert ?? nameValueSubmit;
    if (button == "Insert")
    {
        if (Session["templist"] == null)
        {

            List<PatientViewModel> lst = new List<PatientViewModel>();

            lst.Add(new PatientViewModel()
            {
                PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
                                        Amount = double.Parse(Request.Form["Amount"]),
                Description = Request.Form["Description"]
            });
            Session["templist"] = lst;
        }
        else
        {
            List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];

            lst.Add(new PatientViewModel()
            {
                PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
                                        Amount = double.Parse(Request.Form["Amount"]),
                Description = Request.Form["Description"]
            });
            Session["templist"] = lst;
        }
    }
    else
    {
        if (ModelState.IsValid)
        {
            string username = "";
            HttpCookie cookie = HttpContext.Request.Cookies["AdminCookies"];
            if (cookie != null)
            {
                username = Convert.ToString(cookie.Values["UserName"]);
            }
            tblPatientBill patientbill = new tblPatientBill();
            patientbill.PatientAppointmentID = model.PatientAppointmentID;
            patientbill.Amount = model.AmountTotal;
            patientbill.Description = model.Note;
            patientbill.Discount = model.Discount;
            patientbill.CreatedAt = model.CreatedAt;
            patientbill.CreatedBy = username;
            patientbill.is_active = true;
            db.tblPatientBills.Add(patientbill);
            db.SaveChanges();

            int PatientBill_ID = Convert.ToInt32(patientbill.ID);
            List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
            if (lst != null)
            {
                tblPatientBillDetail billdetail = new tblPatientBillDetail();
                foreach (var item in lst)
                {
                    billdetail.PatientBillID = PatientBill_ID;
                    billdetail.Amount = item.Amount;
                    billdetail.CreatedAt = DateTime.UtcNow;
                    billdetail.CreatedBy = username;
                    billdetail.Description = item.Description;
                    billdetail.is_active = true;
                    db.tblPatientBillDetails.Add(billdetail);
                    db.SaveChanges();
                }
                Session.Clear();
            }
            return RedirectToAction("Print", new { Billid = @PatientBill_ID });
        }
    }
    return View(model);
}

如果其他人遇到相同情况,此问题的解决方案如下所示:在 ViewModel 中,为下拉列表创建属性以从数据库中检索值并发送所选值到数据库。

CreateBillViewModel:

public class CreateBillViewModel
{
-------- --------
public IEnumerable<SelectListItem> PatientAppointmentDate { get; set; }
public int PatientAppointmentID { get; set; }
-------- --------
}

控制器中:

  public ActionResult Create(int? Patient_id)
  {
  CreateBillViewModel model = new CreateBillViewModel();
  if (Patient_id != null)
  {
  model.PatientAppointmentDate = (from p in db.tblPatientAppointments
  where p.patient_id == Patient_id
  select new SelectListItem
  {
  Text = p.AppointmentDate,
  Value = p.ID.ToString()
  }).ToList();
  }
  return View(model);
  }

像这样在视图中检索它:

查看:

@Html.DropDownListFor(m => m.PatientAppointmentID, Model.PatientAppointmentDate ?? new List<SelectListItem>(), "- Select Appointment Date - ", new { @class = "form-control" })

提交表单后,如果您希望打开相同的页面并希望在下拉列表中使用相同的值,那么在 HTTPPOST 中将其发回,就像这样。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateBillViewModel model, int? Patient_id)
{
if (ModelState.IsValid)
{
//Save into db
}
model.PatientAppointmentDate = (from p in db.tblPatientAppointments
where p.patient_id == Patient_id
select new SelectListItem
{
Text = p.AppointmentDate,
Value = p.ID.ToString()
}).ToList();
}
return View(model);
}

我的问题就是这样resolved.For进一步详细说明这个link可以参考: