0

I'm trying to get the drop down list to have my item selected when there is an item, but it never does. I've Googled this and tried many different methods, but they all seem to use a ViewModel containing the list instead of using ViewBag, but I would like to stick to the ViewBag if possible.

My controller:

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

My View:

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

This doesn't have my item selected in the DropDownList, and I've also tried having a list in the ViewBag and then constructing the SelectList in the View, which some posts say should solve the problem:

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

But none of it seems to work. So I was wondering if there is anyone where that is able to spot what I'm doing wrong?

4

2 回答 2

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...")
于 2012-08-13T00:48:55.127 回答
0

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

if (id.HasValue)
        {
            var model = rep.GetItemByID(id.Value);
            model.itemID=id.Value;
            return View(model);
        }
于 2012-08-12T22:33:50.943 回答