【发布时间】:2019-03-19 17:53:04
【问题描述】:
我在尝试在索引页面中加载部分视图时遇到问题,站点显示的错误如下:
没有具有键“QuestionType”的“IEnumerable”类型的 ViewData 项基本上问题似乎出在下拉 html 中。
这是我的部分:
<div class="form-group">
@Html.LabelFor(model => model.QuestionType, "QuestionType", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("QuestionType", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.QuestionType, "", new { @class = "text-danger" })
</div>
</div>
我的问题控制器
public ActionResult Create()
{
ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name");
return View();
}
// POST: MyQuestions/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,Description,QuestionDate,Tags,QuestionType")] MyQuestion myQuestion)
{
if (ModelState.IsValid)
{
db.MyQuestions.Add(myQuestion);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name", myQuestion.QuestionType);
return View(myQuestion);
}
这就是我如何称呼部分:
<div class="modal-body">
@Html.Partial("_CreatePartial", new MyWebAppInMVC.Database.MyQuestion())
</div>
在部分的顶部,我使用以下行:
@using (Html.BeginForm("Create", "MyQuestions", FormMethod.Post, new { id = "AddModal" }))
我的代码有什么问题?
【问题讨论】:
-
您正试图从模型中获取 QuestionType,但它在视图包中(这是一种不好的做法,您应该立即放弃,而支持通过 ViewModel 进行正确的模型绑定)
-
这段代码基本上是从Visual Studio自动生成的。
-
但这基本上是错误的,不是吗? ;)
-
是的,我该怎么办?那么,我的代码应该是什么样子?
标签: c# asp.net asp.net-mvc entity-framework