【问题标题】:MVC There is no ViewData item of type 'IEnumerable<SelectListItem> on Post ActionMVC Post Action 上没有 'IEnumerable<SelectListItem> 类型的 ViewData 项
【发布时间】:2016-05-29 15:00:02
【问题描述】:

我在 MVC 中遇到 DropDownList 问题, 我可以在 HTTPGET 上填充下拉列表,即数据输入页面显示下拉列表,其中包含来自数据表的正确数据,但是只要我按下提交按钮,MVC 就会将我带到 DropDownList 的查看器行,并出现错误“没有 ViewData 类型的项目”具有键 'Suburb' 的 IEnumerable'"

我的模特是

   public  class ServiceEntryRegister
{
    public List<ReceiptHeader> HEADER { get; set; }
    public List<ReceiptDetail> DETAIL { get; set; }

    public ReceiptHeader SingleHEADER { get; set; }
    public ReceiptDetail SingleDETAIL { get; set; }

}

控制器

[HttpGet]
    public ActionResult CreateNew()
    {

        ServiceEntryRegister Model = new ServiceEntryRegister();
        ViewBag.Btype = new SelectList(_er.BodyTypes, "Bodytypeid", "btype");
        ViewBag.Engine = new SelectList(_er.EngineTypes, "Enginetypeid", "Engine");
        ViewBag.Suburb = new SelectList(_er.Suburbs, "SuburbID", "SuburbName");
        ViewBag.VehicleMake = new SelectList(_er.VehicleMakes, "VehicleMakeID", "Make");

        return View();
    }


    [HttpPost]
//    [ValidateAntiForgeryToken]
    public ActionResult CreateNew(ServiceEntryRegister RH)
    {
        if (ModelState.IsValid)
        {
            CreateBagForLists();
            RH.SingleHEADER.ReceiptID = _HC.PrimaryKeyGenerater();
            _er.ReceiptHeaders.Add(RH.SingleHEADER);
            _er.SaveChanges();
            return View();
        }
        else
        {
            return View();
        }
    }

视图是:

<td>@Html.DropDownList("Suburb", String.Empty)</td>

我也试过了:

<td>@Html.DropDownList("Suburb", ViewBag.Suburb as SelectList)</td>

但一切都是徒劳的。

【问题讨论】:

标签: asp.net-mvc selectlist


【解决方案1】:

我建议避免使用 viewbags 并使用强类型下拉列表。 在您的方法中,您必须在两个操作(发布和获取)中绑定视图包以克服此错误。

【讨论】:

  • 亲爱的 Anupam,您能否提供代码来强绑定列表视图,因为我是 MVC 新手。并想确认我的做法是正确的
猜你喜欢
  • 2016-05-11
  • 2014-01-12
  • 2017-07-15
  • 1970-01-01
  • 2019-05-16
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多