【问题标题】:DropDownListFor doesn't display selected itemDropDownListFor 不显示所选项目
【发布时间】:2012-08-12 22:24:47
【问题描述】:

我试图让下拉列表在有项目时选择我的项目,但它从来没有。我用谷歌搜索过这个并尝试了许多不同的方法,但它们似乎都使用包含列表的 ViewModel 而不是使用 ViewBag,但如果可能的话,我想坚持使用 ViewBag。

我的控制器:

    [HttpGet]
    public ActionResult Index(int? id)
    {
        ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type");
        if (id.HasValue)
        {
            var model = rep.GetItemByID(id.Value);
            if ( model != null )
            {
                return View(model);
            }
        }
        return View();
    }

我的观点:

    <div class="editor-field">
        @Html.DropDownListFor(model => model.itemID, (SelectList)ViewBag.SelectList)
        @Html.ValidationMessageFor(model => model.itemID)
    </div>

这并没有在 DropDownList 中选择我的项目,我也尝试在 ViewBag 中有一个列表,然后在 View 中构造 SelectList,有些帖子说这应该可以解决问题:

    <div class="editor-field">
        @Html.DropDownListFor(model => model.itemID, new SelectList(ViewBag.SelectList, "id", "type", Model.itemID))
        @Html.ValidationMessageFor(model => model.itemID)
    </div>

但似乎都不起作用。所以我想知道是否有人能够发现我做错了什么?

【问题讨论】:

    标签: asp.net-mvc-3 razor html.dropdownlistfor


    【解决方案1】:

    确保您的 itemID 属性已在您传递给视图的模型中设置

    if (id.HasValue)
            {
                var model = rep.GetItemByID(id.Value);
                model.itemID=id.Value;
                return View(model);
            }
    

    【讨论】:

    • 当我从 rep.GetItemByID(id.Value); 获取模型时itemID 始终设置。但另一方面,这确实向我指出,我需要确保用于该项目的 id 返回一个项目。我的问题仍未解决。
    【解决方案2】:

    由于 SelectList 是不可变的,我会尝试从一开始就设置选定的值。

      [HttpGet]
            public ActionResult Index(int? id)
            {
                if (id.HasValue)
                {
                    ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type", id );
                    var model = rep.GetItemByID(id.Value);
                    if ( model != null )
                    {
                        return View(model);
                    }
                }
                else
                {
                    ViewBag.SelectList = new SelectList(rep.GetItemList(), "id", "type");
                }
                return View();
            }
    

    在您的视图中像这样使用它:

    @Html.DropDownListFor(model => model.itemID, (SelectList)ViewBag.SelectList, "Please select...")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多