![](/img/trans.png)
[英]How to handle API responses globally in ASP.NET MVC controller?
[英]Properly handle ModelView responses in MVC EF ASP.NET
我必須建模,例如A和B
public class A
{
public int AID {get; set; }
public string Name {get; set;}
public virtual B B {get; set;}
}
public class A
{
[ForeignKey("A")]
public int BID {get; set; }
public string Name {get; set;}
public virtual A A {get; set;}
}
還有一個ViewModel
public class ABViewModel
{
public A A {get;set;}
public B B {get;set;}
}
然后我想要一個視圖,該視圖允許我同時設置兩個模型的名稱,因此控制器看起來像
public ActionResult Create()
{
var viewModel = new ABViewModel();
return View(viewModel);
}
到目前為止,效果如何? 如下所示返回錯誤
值不能為空。 參數名稱:實體
public ActionResult Create([Bind(Include = "A, B")] ABViewModel stuff)
{
if (ModelState.IsValid)
{
db.A.Add(stuff.A); // <-- here occurs the error
stuff.B.A = stuff.A;
db.B.Add(stuff.B);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(stuff);
}
這次您不需要ViewModels。
您的A
包含B
而B
包含A
第一。 選擇其中一個,讓我選擇A
public ActionResult Create() {
var model = new A();
model.B = new B();
return View(model);
}
然后在“視圖”上修改A內容和AB內容
public ActionResult Create([Bind] A stuff)
{
if (ModelState.IsValid)
{
db.A.Add(A);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(stuff);
}
一旦A包含B,則無需添加B。B的ModelState將也設置為ModelState.Added
。
回答你的問題。 在該行上: db.A.Add(stuff.A);
A
不包含已初始化的B
實例。 AB
為空。 這就是為什么您會得到一個錯誤。
您必須首先將B
添加到A
,然后保存數據庫。 如果您確實要創建ViewModel,請執行以下操作:
stuff.A.B = stuff.B;
db.A.Add(stuff.A); // <-- Here is all good cause now A contains B.
stuff.B.A = stuff.A; // there is no need for it anymore
db.B.Add(stuff.B); // no need, B was already added on A.Add(...)
db.SaveChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.