我是MVC的新手。我使用DropDownListFor來選擇公司時填充許多Customer字段。我使用下面的代碼爲DropDownListFor:DropDownListFor的值不能爲空
@Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "Company"), "---Select one---", new { htmlAttributes = new { @class = "company" } });
@Html.HiddenFor(model => model.Company)
此代碼檢索客戶數據:
[HttpPost]
public ActionResult GetCustomer(int custId)
{
var data = db.Customers.Find(custId);
return Json(data);
}
在視圖模型的相關領域(從客戶表)有:
public int CustomerId { get; set; }
public string Company { get; set; }
Create方法中創建ViewBag的代碼:
public ActionResult Create()
{
QuoteViewModel qvm = new QuoteViewModel();
qvm.QuoteDetail = new List<QuoteDetail>();
var customers = db.Customers.ToList();
ViewBag.Customers = customers;
return View(qvm);
}
這裏是爲POST代碼:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QuoteViewModel qvm)
{
if (ModelState.IsValid)
{
Quote quote1 = new Quote();
quote1.CustomerId = qvm.CustomerId;
...
db.Quotes.Add(quote1);
customer.CustomerId = qvm.CustomerId;
...
db.Entry(customer).State = EntityState.Modified;
bool saveFailed;
do
{
saveFailed = false;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
saveFailed = true;
var objContext = ((IObjectContextAdapter)db).ObjectContext;
// Get failed entry
var entry = ex.Entries.Single();
// Now call refresh on ObjectContext
objContext.Refresh(RefreshMode.ClientWins, entry.Entity);
}
} while (saveFailed);
return RedirectToAction("Index");
}
return View(qvm);
}
領域的人口工作正常,但是當我試圖創建視圖模型我上DropDownListFor錯誤「值不能爲空」。我研究過有這個問題的其他人,但找不到適用於此案例的答案。任何幫助將非常感激。
這是發生在你提交了(你需要顯示你的POST方法,用於Create()' –
添加上面。謝謝Stephen。 –