简体   繁体   中英

Set default dropdown defalut value based on viewbag

I have a dropdown list that reloads the page when its selected value is changed. This works and renders as expected. The only problem is that the dropdown list goes back to the default value. How can I change the the default value to match 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;
    });

the controller sets ViewBag.Level based on the param passed in

You could add a property to your view model which will be an IEnumerable<SelectListItem> which you will initialize like that in your controller. Then just set the LevelId property to a value you would like to preselect:

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

and then in your view:

@Html.DropDownListFor(model => model.LevelId, Model.Items)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM