EFを使用して新しいdbオブジェクトを作成する際に問題が発生しています。これには、プリセットビューを使用するときにドロップダウンメニューを使用して設定される外部キーがあります。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);
}
これはどのような方法で実現できますか?
...あなたのDropDownListコントロールで「無効」属性を追加しますか?それは(あなたのケースでは理にかなって) 'Create'アクション –
メイクに渡され、メソッド 'public ActionResult Create(int ID)'を呼び出し、モデルを返すビューに( 'ParentId'が' ID'の値に設定されている)、ビューで '@Html.HiddenFor(m => m.ParentId)' –