我在使用EF创建新的数据库对象时遇到了问题。它有一个外键,在使用预设视图时,可以使用下拉菜单进行设置。MVC设置外键没有下拉
@Html.DropDownList("ParentID", null, htmlAttributes: new { @class = "form-control" })
的问题是,我不希望编辑该值,则需要在控制器中进行设置,但我不能访问的价值。
public ActionResult Create()
{
//I don't want a select list ParentID needs to be passed from the parent.
ViewBag.ParentID = new SelectList(db.Parents, "ParentID", "ParentName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ChildID,ParentID,ChildName")] Child child)
{
if (ModelState.IsValid)
{
//How do I set child.ParentID without a select list???
db.Child.Add(child);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ParentID = new SelectList(db.Parents, "ParentID", "ParentName", child.ParentID); //I don't need this
return View(child);
}
这是通过什么方式实现的?
的问题是,你在哪里想要得到的parentId的呢?是不是传递给'Create'行动(这是有道理的,你的情况) –
制作'public ActionResult Create(int ID)'方法并返回一个模型('ParentId'设置为'ID'的值),然后在视图中使用'@ Html.HiddenFor(m => m.ParentId)' –