无法获得asp.net MVC4 DropDownList()以获得预设值

led*_*per 2 c# asp.net asp.net-mvc asp.net-mvc-4

我没有看到任何关于如何通过ViewBag做到这一点的答案.(我知道我们都讨厌ViewBag,我应该使用ViewModel.不过我的问题,我需要知道如何在不设置ViewModel的情况下完成它).

这是我的控制器设置为页面的GET请求:

var states = Ctx.States.ToList()
            .Select(state => new SelectListItem
            {
                Text = state.Name,
                Value = state.Name
            }).OrderBy(x => x.Text).ToList();

ViewBag.SelectedStateOne = new SelectList(
                        states, 
                        "Text", 
                        "Value", 
                        user.Applicant.FinancialAidInformation.FinancialAidContacts
                        .ElementAtOrDefault(0).Address.State.Name);

ViewBag.SelectedStateTwo = states;
Run Code Online (Sandbox Code Playgroud)

我正在以两种不同的方式设置viewbag.两种方式似乎都正确地绑定下拉,并正确地回发所选值.但是当我回到页面时,默认选择不是数据库中的值.

在我看来:

@Html.DropDownList("SelectedStateOne", null, new { @class = "form-control" })
@Html.DropDownList("SelectedStateTwo", null, new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

相同的下降,但显示两者,以避免混淆我猜.我认为我使用SelectedStateOne viewbag数据做的是设置默认值的正确方法,但没有骰子.我哪里错了?

Joh*_*n H 5

由于您要指定默认值,因此使用SelectList更简单的方法,所以让我们使用它.

首先,您的原始查询是不必要的.A SelectList可以使用a构建IEnumerable<T>,这意味着您不必SelectListItem首先投射到s.所以这:

var states = Ctx.States.ToList()
            .Select(state => new SelectListItem
            {
                Text = state.Name,
                Value = state.Name
            }).OrderBy(x => x.Text).ToList();
Run Code Online (Sandbox Code Playgroud)

变为:

var states = Ctx.States.OrderBy(x => x.Name).ToList();
Run Code Online (Sandbox Code Playgroud)

现在您只需将列表分配给ViewBag使用您的Name属性:

// Removed the long type name for clarity
ViewBag.SelectedStateOne = new SelectList(states, "Name", "Name", YourSelected.State.Name);
Run Code Online (Sandbox Code Playgroud)

视图中的调用保持不变:

@Html.DropDownList("SelectedStateOne", null, new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

如果仍未选择正确的项目,请仔细检查以确保列表中YourSelected.State.Name存在该项目states.