Keeping a DropDownList value across a post request in MVC

Who hasn’t, as least once in their lives, needed to persist the value of a DropDownList after a POST request in MVC? No one, that’s who. So here we go.

I first populate a List of SelectListItems in my Repository:

        public static List<SelectListItem> PopulateUsers() {
            List<SelectListItem> items = new List<SelectListItem>();
            // yada yada yada
            return items;
        }

In my case, I wanted to store the items in a Cache variable:

        private void PopulateCacheVariables() {
            if (HttpRuntime.Cache["Users"] == null) {
                HttpRuntime.Cache.Insert("Users", Repository.PopulateUsers(), null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 8, 0, 0));
            }
        }

In the GET request in the controller that returns my view, I create a SelectList that holds my wonderful list of items:

        public ActionResult ManageUsers() {
            PopulateCacheVariables();
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text");
            return View();
        }

In my view, I create a DropDownList and populate using my ViewBag variable:

@Html.DropDownList("User", (SelectList)ViewBag.Users, "--Select User--", new { @class = "form-control" })

Finally, the good part. I perform some validation (not all shown here) to make sure that the required fields are provided. If they are not, then I tell the ModelState to become invalid. If the ModelState.IsValid check is false, the “else” section executes. In this section, I create the SelectList using an extra parameter, the currently selected user, to persist that value when the view is returned.

If all the required fields were selected, then the process completes successfully and the SelectList is generated with no extra parameter so the value is not persisted and the field resets to its default value.

    [HttpPost]
    public ActionResult ManageUsers(TheUser model) {
       if (!String.IsNotNullOrEmpty(Request["Application"])) {
           ModelState.AddModelError("Application", "Application is required");
       }
       if (ModelState.IsValid) {
            AppHubRepository.CreateUser(Request["User"], Request["Application"]);
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text");
        } else {
            ViewBag.Users = new SelectList((List<SelectListItem>)HttpRuntime.Cache["Users"], "Value", "Text", Request["User"]);
        }
        return View(model);
    }

 

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: