c# - 部分页面 Asp.NET IEnumerable 中没有 ViewData
问题描述
我在尝试在索引页面中加载部分视图时遇到问题,该站点显示的错误如下:
没有具有键“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" }))
我的代码有什么问题?
解决方案
简单地写你@Html.DropDownList
如下:
@Html.DropDownList("QuestionType", ViewBag.QuestionType as SelectList,"Select Question Type", htmlAttributes: new { @class = "form-control" })
推荐阅读
- c# - Gremlin.NET 是否支持提交异步字节码?
- javascript - Object.create() 混乱 - 你如何访问/销毁对象?
- javascript - 为什么 .vue 中声明的基于 ts-class 的 vue-component 的静态方法只能在 .vue 的脚本块中工作?
- ios - 与“iPhone”启动应用程序 Xcode 11.3.1 上的调试器失去连接
- python - 继承问题:AttributeError: 'Vector' 对象没有属性 '_Vector__i'
- javascript - 匹配 NodeJS Javascript 中 HttpServerUtility.UrlTokenEncode 的输出
- c++ - 在定义的次数和时间内将引脚设置为高电平的功能
- azure - 为什么 CloudConfigurationManager.GetSetting 会锁定或以其他方式表现不佳
- google-apps-script - GAS - 从阵列中删除重复项的问题
- reactjs - 如何在 Gatsby 网站上正确实现 JSONP 表单提交