我需要将所有客户从一个不同的客户表中转移到Tickets表单。
我的模态......
[HttpPost]
public ActionResult Create(Ticket ticket)
{
//Very important step
if (!ModelState.IsValid)
{
return View(ticket);
}
Console.WriteLine("Customer: ");
ViewBag.Customers = new SelectList(context.Customers.ToList());
try {
context.Tickets.Add(ticket);
context.SaveChanges();
}
catch(Exception ex)
{
ModelState.AddModelError("Error:" , ex.Message);
return View(ticket);
}
TempData["Message"] = "Created " + ticket.TicketID;
return RedirectToAction("Index");
}
我的控制器......
<div class="form-group">
@Html.LabelFor(model => model.TicketDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.TicketDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.TicketDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CustomerName, "Customer", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Customers", (IEnumerable<SelectListItem>)(ViewBag.Customers), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CustomerName, "", new { @class = "text-danger" })
</div>
</div>
我的观点.....
{{1}}
我知道有很多帖子,我尝试了所有人。
答案 0 :(得分:1)
首先,您不能将ViewBag
属性命名为与绑定属性相同的属性,但无论如何您似乎想要绑定到CustomerID
,因此您的视图应该是(始终使用强类型{ {1}}方法)
HtmlHelper
接下来,您获得例外的原因是因为 @Html.DropDownListFor(m => m.CustomerID, (IEnumerable<SelectListItem>)(ViewBag.Customers), htmlAttributes: new { @class = "form-control" }
是ViewBag.Customers
。如果在POST方法中返回视图,则必须重新分配null
属性的值。假设ViewBag
包含属性Customers
和CustomerID
,那么GET方法中的代码必须是
CustomerName
和POST方法
ViewBag.Customers = new SelectList(context.Customers, "CustomerID", "CustomerName");
最后,根据您显示的视图,您需要删除具有if (!ModelState.IsValid)
{
// Reassign the SelectList
ViewBag.Customers = new SelectList(context.Customers, "CustomerID", "CustomerName");
return View(ticket);
}
Console.WriteLine("Customer: ");
// ViewBag.Customers = new SelectList(context.Customers.ToList()); Remove this
try {
....
属性的属性public string CustomerName { get; set; }
,这意味着[Required]
始终无效。您有一个下拉列表,用于选择需要绑定到ModelState
的客户,而您没有绑定到CustomerID
的控件(也不应该有一个)