没有类型&#39; IEnumerable <selectlistitem>&#39;的ViewData项目。具有键&#39; M_TYPE&#39; </selectlistitem>

时间:2015-01-21 10:05:03

标签: asp.net-mvc-4

这是我的控制器动作

        [HttpGet]
    public ActionResult AddDrug()
    {
        UserDB db = new UserDB();
        ViewData["MedType"] = new SelectList(db.mtype, "MID", "M_TYPE");
        return View();
    }

这是For Post Method

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AddDrug(Drug drug)
    {
        UserDB db = new UserDB();
        if (ModelState.IsValid)
        {
            db.drugs.Add(drug);
            db.SaveChanges();
            ModelState.Clear();
            TempData["AlertMessage"] = "Medicine Type Added Sucessfully";
            return View();
        }
        return View(drug);
    }

这是我的观点

<div class="editor-label">
        @Html.LabelFor(model => model.M_TYPE)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.M_TYPE,ViewData["MedType"] as IEnumerable<SelectListItem>,"(none)")
        @Html.ValidationMessageFor(model => model.M_TYPE)
    </div>

现在我不会将下拉列表中的数据插入到数据库中,但它会通过该错误

1 个答案:

答案 0 :(得分:2)

当您返回视图时,您需要重新分配SelectList,否则它是null,这会导致该异常(另请参阅有关重定向的说明)

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDrug(Drug drug)
{
    UserDB db = new UserDB();
    if (ModelState.IsValid)
    {
        db.drugs.Add(drug);
        db.SaveChanges();
        // ModelState.Clear(); // don't do this!
        TempData["AlertMessage"] = "Medicine Type Added Sucessfully";
        // return View(); // don't do this!
        return RedirectToAction("AddDrug"); // do this instead
    }
    ViewData["MedType"] = new SelectList(db.mtype, "MID", "M_TYPE"); // add this
    return View(drug);
}