DropDownListFor与ViewBag获取null

时间:2014-06-17 14:07:46

标签: c# asp.net razor

控制器:

using (ISession session = NHIbernateSession.OpenSession())
    {                
      var item = session.Query<CarModel>().ToList();
      ViewBag.Modas = item;
      return View();
    }

查看:

   <div class="form-group">
                @Html.LabelFor(model => model.Modelis.model_name, new { @class = "control-label col-md-2" })
                <div class="col-md-10">                    
                    @Html.DropDownListFor(model => model.Modelis.Id, new SelectList(ViewBag.Modas, "Id", "model_name"), "--Select Cars--")                       
                </div>
            </div>

控制器(提交部分):

[HttpPost]
public ActionResult Create(Transport item)
{
    try
    {
        using (ISession session = NHIbernateSession.OpenSession())
        {
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(item);
                transaction.Commit();
            }
        }

        return RedirectToAction("Index");
    }
    catch (Exception exception)
    {
        return View();
    }
}

我在提交时收到错误:

值不能为空。 参数名称:项目

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.ArgumentNullException:值不能为null。 参数名称:items

我不明白出了什么问题

1 个答案:

答案 0 :(得分:0)

参考您提交的代码,您似乎正在使用MVC的强类型视图。在这种情况下,您应该为视图提供模型。 您正在返回视图而未提供或指定模型。因此,您的视图将模型设为null。请提供型号并检查执行情况。

using (ISession session = NHIbernateSession.OpenSession())
    {                
      var item = session.Query<CarModel>().ToList();
      ViewBag.Modas = item;
      // Either set the model like .... ViewData.Model = new YOUR_MODEL_CLASS();
     // OR return your model by view constructor like.. return View(new YOUR_MODEL_CLASS());
      return View();
    }