下拉列表mvc3中的所选项目

时间:2013-03-16 08:13:23

标签: asp.net-mvc-3 dropdownlistfor

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>

secound选择完美,第一个(类)不会在页面加载时选择所选项目。

并且对于记录,存储在数据库中的值是C. 请帮忙!!!

1 个答案:

答案 0 :(得分:3)

真是...... !!!!

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