【问题标题】:DropDownListFor with ViewBag getting null带有 ViewBag 的 DropDownListFor 为空
【发布时间】:2014-06-17 14:07:46
【问题描述】:

控制器:

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:值不能为空。 参数名称:items

我不明白怎么回事

【问题讨论】:

  • 能否提供用于提交的控制器方法。具体来说,方法签名是什么样的?抛出异常的代码是什么样的?
  • 您没有在控制器中指定模型,因此对model 的任何引用都将是null

标签: c# asp.net razor


【解决方案1】:

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

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();
    }

【讨论】:

  • 你的建议我该怎么做?
  • 好吧,如果你正在做类似的事情...... @Html.DropDownListFor(model => ......那么它需要一个模型来引用视图页面。你必须有一个强类型视图。因此,您应该初始化模型并从控制器操作方法将其分配给视图。
  • 如果您不知道 MVC 中的强类型视图是什么,请参考这篇文章 ..stackoverflow.com/questions/2896544/…
  • 但是如果我删除带有模型的 DropDownListPart 其他一切正常,@Html.LabelFor(model => model.lic_plate... 等等都可以工作。还是我误解了?
  • Html.LableFor 可以正常工作,因为它不需要模型实例。它只是按类型访问属性名称。您必须为视图分配正确的模型实例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-29
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多