如何在我的控制器中设置一个值,使我的视图将该值更新到数据库中?如何将值传递给控制器中的CREATE函数?
我的控制器功能:
public ActionResult Create([Bind(Prefix = "id")]int testid)
{
if (testid != 0)
{
ViewBag.sectionid = new SelectList(db.section, "id", "name");
ViewBag.testid =new SelectList(db.test.Where(t => t.id == testid), "id", "name");
return View();
}
else
{
return View("mislukt");
}
}
//
// POST: /TestSection/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(testsection testsection)
{
if (ModelState.IsValid)
{
db.testsection.Add(testsection);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.sectionid = new SelectList(db.section, "id", "name", testsection.sectionid);
ViewBag.testid = new SelectList(db.test, "id", "name", testsection.testid);
return View(testsection);
}
我的观点: testsection
<div class="editor-label">
@Html.LabelFor(model => model.testid, "test")
</div>
<div class="editor-field">
@Html.DropDownList("testid", String.Empty)
@Html.ValidationMessageFor(model => model.testid)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.sectionid, "section")
</div>
<div class="editor-field">
@Html.DropDownList("sectionid", String.Empty)
@Html.ValidationMessageFor(model => model.sectionid)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.mindifficulty)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.mindifficulty)
@Html.ValidationMessageFor(model => model.mindifficulty)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.maxdifficulty)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.maxdifficulty)
@Html.ValidationMessageFor(model => model.maxdifficulty)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.questioncount)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.questioncount)
@Html.ValidationMessageFor(model => model.questioncount)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.weight)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.weight)
@Html.ValidationMessageFor(model => model.weight)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
这个工作,但给了我这样的:
,我想这一点:
我尝试了使用:
ViewBag.testid = db.test.Where(t => t.id == testid);
,然后就设置这样的观点:
<div class="editor-field">
@ViewBag.testid
@Html.ValidationMessageFor(model => model.testid)
</div>
但我得到一个FK约束当我这样做。
有人知道我能得到我想要的结果吗?
那么我该如何将ViewBag链接到它呢? – kicked11
您将不会使用ViewBag,而是将值分配给您的模型中的某个属性,并使用与该属性关联的TextBoxFor – CSharper