0
我有兩個模型發票和客戶端,它們具有一對多的關係。我的問題是當我嘗試創建一個新的發票時,由於Client對象的必填字段未填充,所以modelstate變爲false。我試圖設置默認值,例如int property {get; set;} = 1;
,但是當我嘗試檢索關係模型時,這會導致覆蓋屬性值。我是新來的asp.net任何幫助,將不勝感激。ModelState對於與必填字段的關係爲false
這裏是我的客戶模型代碼:
public class Client
{
public int ClientId { get; set; }//Primary key
[Required]
[Display(Name = "Client/Company Name")]
public string Name { get; set; }
//.....
public List<Invoice> Invoices { get; set; }
}
發票型號:
public class Invoice
{
public int InvoiceId { get; set; }//Primary key
[Required]
[Display(Name = "Client/Company Name")]
public int ClientId { get; set; }//Foreign key
public Client client { get; set; }
//....
}
我的代碼保存發票:
[HttpPost]//Save quote & redirect to edit quote
public IActionResult Create(Invoice quote)
{
ViewData["Title"] = "Create Quotation";//Set title of the view!
if (ModelState.IsValid)//If quote is validated to true.
{
_context.Invoices.Add(quote);//insert quote
_context.SaveChanges();
//Redirect to edit page to add items to the invoice
return RedirectToAction("Edit", new { id = quote.InvoiceId });
}
//...
}
我的代碼與他們的客戶取得發票名稱
public IActionResult Index()
{
ViewData["Title"] = "Quotations";//Set title of the view!
//Return with array of all quotations.
return View(_context.Invoices.Include(i => i.client).Where(i => i.isQuote == true).ToArray());
}
任何提示或幫助,將不勝感激。
你,因爲你正在使用的實體模型作爲的ViewModels得到這個問題。創建一個單獨的CreateInvoiceViewModel,它只有一個ClientID,並在持久時將其映射到適當的類。 – CodeCaster
@CodeCaster是這樣的在asp.net中做到這一點,我的意思是這是一種常見的做法? – theMohammedA
定義「這個」?使用視圖模型?是的,這在MVC中是非常普遍的做法,實際上它是這種設計模式的基石之一。不幸的是,幾乎所有的ASP.NET MVC教程都使用實體模型作爲視圖模型,由於您現在遇到的原因,這是一個糟糕的做法。 – CodeCaster