【问题标题】:Error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Customer'错误:没有具有键“客户”的“IEnumerable<SelectListItem>”类型的 ViewData 项
【发布时间】:2016-02-21 06:02:27
【问题描述】:

我需要将所有客户从一个不同的表中获取到门票表格中。

我的模态......

public class Ticket
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required()]
    public Int32 TicketID { get; set; }
    public Int32 TicketNum { get; set; }
    [Required()]
    public DateTime TicketDate { get; set; }

    [ForeignKey("Customer")]
    public Int32 CustomerID { get; set; }
    [Required(ErrorMessage ="Customer Name is required!!")]
    [Display(Name ="Customer Name")]
    public String CustomerName { get; set; }

    public Int32 FieldID { get; set; }
    public Int32 WellID { get; set; }
    public Int32 WellName { get; set; }
    public Int32 LogID { get; set; }

    public IEnumerable<SelectListItem> Customers { get; set; }
    public virtual Customer Customer { get; set; }
  //  public virtual Field Field { get; set; }
   // public virtual Well Well { get; set; }
  //  public virtual Log Log { get; set; }

}

我的控制器...

[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>

我知道有很多关于此的帖子,我尝试了每个人。

【问题讨论】:

    标签: asp.net-mvc ef-code-first


    【解决方案1】:

    首先,您不能将ViewBag 属性命名为与您绑定到的属性相同,但看起来您无论如何都想绑定到CustomerID,所以您的视图应该是(始终使用强类型的HtmlHelper 方法)

     @Html.DropDownListFor(m => m.CustomerID, (IEnumerable<SelectListItem>)(ViewBag.Customers), htmlAttributes: new { @class = "form-control" }
    

    接下来,您得到异常的原因是因为ViewBag.Customersnull。如果在 POST 方法中返回视图,则必须重新分配 ViewBag 属性的值。假设Customers包含属性CustomerIDCustomerName,那么GET方法中的代码需要是

    ViewBag.Customers = new SelectList(context.Customers, "CustomerID", "CustomerName");
    

    在 POST 方法中

    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 {
        ....
    

    最后,根据您显示的视图,您需要删除具有[Required] 属性的属性public string CustomerName { get; set; },这意味着ModelState 将始终无效。您有一个用于选择需要绑定到 CustomerID 的客户的下拉列表,并且您没有用于绑定到 CustomerName 的控件(您也不应该拥有)

    【讨论】:

    • 您好斯蒂芬,非常感谢您的快速回复。我试过你上面提到的......但我的 ViewBag.Customers 仍然为空......我不确定发生了什么......我的数据库连接很好,而且我在客户表中也有数据......我对 MVC 很陌生,真的需要尽快解决这个问题....请建议
    • 那么context.Customers.ToList()返回的是什么?除非它返回 List&lt;String&gt;,否则它将不起作用 - 它需要是 ViewBag.Customers = new SelectList(context.Customers, "CustomerID", "CustomerName");(在 GET 和 POST 方法中)假设 Customers 包含这两个属性
    • 是的,Customers 表有这两个属性..我尝试检查 context.Customers.ToList() 返回的值 ...但我无法在输出控制台看到任何值...请指教我
    • 首先我将编辑我的问题。但是如果context.Customers.ToList() 返回null 那么这是一个完全不同的问题,因为与您显示的任何代码都无关
    • 我的回答指出了代码中的 3 个错误。最初只是通过在视图中替换使用 @Html.DropDownList("Customers", Enumerable.Empty&lt;SelectListItem&gt;()) 来测试它。该错误将消失,尽管它不会显示任何选项。至于为什么var customers = context.Customers.ToList()返回null,那你需要调试你的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2020-06-28
    • 2020-08-20
    相关资源
    最近更新 更多