ASP.NET剃须刀下拉选择

ASP.NET剃须刀下拉选择,asp.net,asp.net-mvc,asp.net-mvc-4,razor,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Razor,我有一个字符串列表,并且在这些字符串中有一个选定项。 控制器: ViewBag.GroupName = new SelectList(Names, Names.Find(s=>s==Place.GroupName)); 视图: @Html.DropDownListFor(model=>model.GroupName,(IEnumerable)ViewBag.GroupName) 但视图上的选择始终是列表中的第一项,这与预期不符。 可能有什么问题。试着按以下方式列出您的列表: @Html

我有一个字符串列表,并且在这些字符串中有一个选定项。
控制器:

ViewBag.GroupName = new SelectList(Names, Names.Find(s=>s==Place.GroupName));
视图:

@Html.DropDownListFor(model=>model.GroupName,(IEnumerable)ViewBag.GroupName)
但视图上的选择始终是列表中的第一项,这与预期不符。
可能有什么问题。

试着按以下方式列出您的列表:

@Html.DropDownListFor(model => model.GroupName, (IEnumerable<SelectList>)ViewBag.GroupName)
@Html.DropDownListFor(model=>model.GroupName,(IEnumerable)ViewBag.GroupName)

您还应向SelectList提供有关文本/值的信息。我假设名称是一个字符串列表,所以您应该这样做:

名称创建SelectListItem列表

ViewBag.GroupName = (from s in Names
                     select new SelectListItem
                     {
                         Selected = s == Place.GroupName, 
                         Text = s,
                         Value = s
                     }).ToList();
然后在视图中使用它:

@Html.DropDownList("GroupName") /*Will get from the ViewBag the list named GroupName*/

您需要确保传递给
Html.DropDownListFor
的第一个参数设置为当前应选择的
SelectListItem
的值。如果其值与DropDownList中的任何值不匹配,则不会将任何项设置为选中项

在您的情况下,您需要确保
model.GroupName
设置为当前应选择的SelectListItem的值

示例:

.cs:

@Html.DropDownList("GroupName") /*Will get from the ViewBag the list named GroupName*/
class myViewModel
{
    public string SelectedValue = "3";
    public List<SelectListItem> ListItems = new List<SelectListItem>
        {
            new SelectListItem { Text = "List Item 1", Value = "1"},
            new SelectListItem { Text = "List Item 2", Value = "2"},
            new SelectListItem { Text = "List Item 3", Value = "3"}
        };
}
@model myViewModel

@Html.DropDownListFor(m => m.SelectedValue, Model.ListItems)