DropDownListFor不显示所选项目

时间:2012-08-12 22:24:48

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

我正在尝试获取下拉列表,以便在有项目时选择我的项目,但它永远不会。我已经用Google搜索并尝试了许多不同的方法,但它们似乎都使用包含列表的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>

但似乎没有任何效果。所以我想知道是否有人能够发现我做错了什么?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我会尝试从开头设置所选值,因为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...")