0

我有一个下拉列表,当其选定值发生更改时会重新加载页面。这可以正常工作并按预期呈现。唯一的问题是下拉列表回到默认值。如何更改默认值以匹配 ViewBag.Value?

 @Html.DropDownListFor(model => model.LevelId,
                            (
                                from choice in
                                    (from p in Model.Defaults
                                     group p by new { p.LevelId, p.LevelDescription } into c
                                     select new { c.Key.LevelId, c.Key.LevelDescription })
                                select new SelectListItem
                                           {
                                               Text = choice.LevelDescription,
                                               Value = choice.LevelId.ToString(),
                                               Selected = false
                                           }))

脚本

$("#LevelId").change(function() {

        var clientId = @Model.ClientId;
        var compareDate = $("#EffectiveDate").val();
        var level = $(this).val();
        var params = $.param({ clientId: clientId, compareDate: compareDate, level : level });
        var link = '@Url.Action("Create", "Choices")'; //"\\Choices\\RefreshView";
        var url = link + "?" + params;
        document.location = url;
    });

控制器根据传入的参数设置 ViewBag.Level

4

1 回答 1

1

您可以向视图模型添加一个属性,该属性将是IEnumerable<SelectListItem>您将在控制器中初始化的属性。然后只需将 LevelId 属性设置为您要预选的值:

public ActionResult Foo(string level)
{
    var model = new MyViewModel();
    var values = from choice in
        (from p in Model.Defaults
         group p by new { p.LevelId, p.LevelDescription } into c
         select new { c.Key.LevelId, c.Key.LevelDescription })
         select new {
             Text = choice.LevelDescription,
             Value = choice.LevelId.ToString()
         }
    );
    model.Items = new SelectList(values, "Text", "Value");
    model.LevelId = level;
    return View(model);
}

然后在你看来:

@Html.DropDownListFor(model => model.LevelId, Model.Items)
于 2012-01-18T17:12:10.930 回答