这也可以;例如:
==> 在“NumberController”文件中:
public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
if (ModelState.IsValid)
{
...
...
return RedirectToAction("Index");
}
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId",
"OperatorSign", number.OperatorId);
return View();
}
==> 在视图文件(Create.cshtml)中:
<div class="form-group">
@Html.LabelFor(model => model.Number1, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Number1, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Number1, "", new { @class =
"text-danger" })
</div>
</div>
现在如果我们删除这个语句:
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);
从以下语句的后面(在我们的控制器中):
return View();
我们会看到这个错误:
没有具有键“OperatorId”的“IEnumerable”类型的 ViewData 项。
* 所以请确保这些陈述的存在。*