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
                                           }))

jscript

$("#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 に答える