如何在我的控制器中設置一個值,使我的視圖將該值更新到數據庫中?如何將值傳遞給控制器中的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