0

Mvc3 dropdownlistFor 让我发疯!!!我有两个使用相同代码(不同的 tevt 和值)的选择,但其中一个不起作用。这是我的控制器代码:

   [Authorize(Roles = "admins")]
        public ActionResult Edit(int id = -1)
        {
            Advertise Advertise = db.Advertises.Find(id);
            if (null == Advertise)
                return View("ProductNotFound");

            var selectListItems = new List<SelectListItem>();
            selectListItems.Add(new SelectListItem { Text = "A", Value = "A", Selected = ("A" == Advertise.Class) });
            selectListItems.Add(new SelectListItem { Text = "B", Value = "B", Selected = ("B" == Advertise.Class) });
            selectListItems.Add(new SelectListItem { Text = "C", Value = "C", Selected = ("C" == Advertise.Class) });
            selectListItems.Add(new SelectListItem { Text = "D", Value = "D", Selected = ("D" == Advertise.Class) });
            ViewBag.Class = new SelectList(selectListItems, "Value", "Text",Advertise.Class);

            var selectListItems2 = new List<SelectListItem>();
            selectListItems2.Add(new SelectListItem { Text = "Image", Value = "Image", Selected = ("Image" == Advertise.FileType) });
            selectListItems2.Add(new SelectListItem { Text = "Flash", Value = "Flash", Selected = ("Flash" == Advertise.FileType) });

            ViewBag.Type = new SelectList(selectListItems2, "Value", "Text",Advertise.FileType);

            return View(Advertise);
        }

这是我的视图代码:

<tr>
        <td class="label">
            @Html.LabelFor(model => model.Class) :
        </td>
        <td class="editor-field">
                @Html.DropDownListFor(model => model.Class, (SelectList)ViewBag.Class)
            @Html.ValidationMessageFor(model => model.Class)
        </td>
    </tr>
    <tr>
        <td class="label">
            @Html.LabelFor(model => model.FileType) :
        </td>
        <td class="editor-field">
                @Html.DropDownListFor(model => model.FileType, (SelectList)ViewBag.Type)
            @Html.ValidationMessageFor(model => model.FileType)
        </td>
    </tr>

第二个选择完美地工作,第一个(类)没有在页面加载时选择所选项目。

并为记录,存储在数据库中的值是C。请帮助!

4

1 回答 1

3

什么……!!!!

我发现选择不工作的原因是:我的变量(ViewBag.Class)的名称与模型中的字段相同!!!我将 ViewBag.Class 更改为 ViewBag.glass (只是为了更改名称)并且它起作用了!!!不管怎么说,还是要谢谢你。我希望它可以帮助有这个问题的人!!!

于 2013-03-16T09:04:04.457 回答