【发布时间】:2016-07-31 20:42:37
【问题描述】:
我有两个模型 Invoice 和 Client,它们具有一对多的关系。我的问题是,当我尝试创建新发票时,modelstate 变为 false,因为未填写 Client 对象的必填字段。我试图设置默认值,例如int property {get; set;} = 1; 但这会导致在我尝试检索关系模型时覆盖属性值。我是 asp.net 的新手,任何帮助将不胜感激。
这是我的客户端模型代码:
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());
}
任何提示或帮助将不胜感激。
【问题讨论】:
-
您遇到此问题是因为您使用实体模型作为视图模型。创建一个单独的 CreateInvoiceViewModel,它只有一个 ClientID,并在持久化时将其映射到适当的类。
-
@CodeCaster 这是在 asp.net 中的做法,我的意思是这是一种常见的做法吗?
-
定义“这个”?使用视图模型?是的,这是 MVC 中非常常见的做法,实际上它是该设计模式的基石之一。不幸的是,几乎所有的 ASP.NET MVC 教程都使用实体模型作为视图模型,由于您现在遇到的原因,这是一种不好的做法。
-
@CodeCaster,酷,感谢您抽出宝贵时间回答这个问题,是的,我一直在关注 Microsoft 的官方文档,并摸不着头脑,为什么它不起作用。您能否将其发布为答案,以便我可以选择它作为接受的答案。
-
对不起,没有时间写一个完整的答案。
标签: asp.net asp.net-core entity-framework-core