Masriyah Masriyah - 6 months ago 24
C# Question

Keeping selected item from dropdown box after page refresh

I have a dropdown box with a list of times for the user to choose from. My problem is that after the user picks their choice and then hits the submit button, the page is refreshed and then the dropdown box is set to default again - how can i have the users choice stay in the dropdown box even after a page reload? I am not sure what part of my code is needed best my Get and Post are long - but if there is a general example that would help.


Here is one of my lists i load into the dropdown box:

IQueryable<User> users = _userRepository.FindAllForOffice(_currentUser.OfficeId);
userViewModel.Users = users.ToSelectList("UserId", "FullName",

foreach (SelectListItem view in userViewModel.Users)
if (!viewData.ContainsKey(view.Text))
viewData.Add(view.Text, view.Value + "|user");

This is adding to the actual dropdown:

userViewModel.ViewData = viewData.ToSelectList("Value", "Key",
return View("UserSummary", userViewModel);

ON MY ASPX.CS page i have the following:


string viewType = null;
viewType = Request.QueryString["viewType"];

{ if (viewType == "user")
viewParams.Add("ViewName", "User Report");
var reportDataSource =
_userService.GetUsersReportData(beginDate, endDate, id);
new List<ReportDataSource> {reportDataSource}, viewParams);

I didn't add all the initialization for all the elements - didn't think it is really needed for this situation



I actually found a solution which was really simple and i guess i was overlooking it. I found that the same way i was passing in the values of the dates i could pass the value of the selected view type and it will remain in dropdown box until changed rather than changing after every page load. I made the additions in my CONTROLLER file in my Get method after the button click.

this is my Post:

    public ActionResult ResultSummary(ResultSummaryViewModel resultSummaryViewModel)
        if (!ModelState.IsValid)
            return View("ResultSummary", resultSummaryViewModel);
        return RedirectToAction("ResultSummary",
                                        beginDate = resultSummaryViewModel.BeginDate,
                                        endDate = resultSummaryViewModel.EndDate,
                                        value = resultSummaryViewModel.Value

And this is my Get:

    public ActionResult ResultSummary(DateTime? beginDate = null, DateTime? endDate = null, string value="")
        var resultSummaryViewModel = new ResultSummaryViewModel();
        resultSummaryViewModel.BeginDate = beginDate;
        resultSummaryViewModel.EndDate = endDate;
        resultSummaryViewModel.Value = value;


The code continues but this is the main part.