【发布时间】:2017-04-06 19:03:49
【问题描述】:
我是 MVC 的新手。选择公司时,我正在使用 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);
}
ViewModel 中的相关字段(来自 Customer 表)是:
public int CustomerId { get; set; }
public string Company { get; set; }
创建 ViewBag 的 Create 方法中的代码:
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 上收到错误“值不能为空”。我研究了其他有此问题的人,但找不到适用于此案例的答案。任何帮助将不胜感激。
【问题讨论】:
-
提交时是否会出现这种情况(需要显示
Create()的POST方法 -
添加在上面。谢谢斯蒂芬。
标签: asp.net-mvc