我是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。 –