Eli Hellmer Eli Hellmer - 1 month ago 7x
ASP.NET (C#) Question

How to reload page with previously entered parameters?

I am working on a code project in Asp.net MVC. I have an issue with redirecting the user after they have completed an action. I have these controllers:

Index Search Page:

public ActionResult Index(){

//this method sets up viewmodel data for search preferences

Viewmodel obj = new Viewmodel();
//set values of dropdowns and searching capabilities
return View("Search", obj);

The user then fills out the search boxes in the view, chooses dropdowns. This will return a post search method that handles the data:

public ActionResult Index(Viewmodel obj, int? page)
data = from i in db.Database
select i;

data = data.Where(x => x.poss == obj.poss);

//PAGING and other data formatting here

return View("Results", data);

Once the result list is displayed, I have a checkbox/button system in the result view that allows the user to select multiple results and mark them as "Good", "Bad" ETC. This is a method that changes the database very simply. My problem is that after the database alters the data, im not sure how to return the user back to the exact result set they were at. A method that returns void doesn't work, and the parameters are not separated, (one whole viewmodel), so i can't simply save the URL and return them back to the unique URL. I want to keep the viewmodel as the parameter. How can I save the viewmodel data that contains their search preferences for use later as well as the page number without changing my method to this:

public ActionResult Index(string dropdown1, string dropdown2, int num......){}


One thing I did was save view model to the session. Then I deserialize in the index method. Something like this in the index method:

public ActionResult AdvancedSearch()

        HttpContext currentContext = System.Web.HttpContext.Current;
        AdvancedSearchViewModel advancedSearchViewModel = (AdvancedSearchViewModel)Session["AdvancedSearchViewModel"];
        if (advancedSearchViewModel == null)
            advancedSearchViewModel = new AdvancedSearchViewModel();
            AddAdvancedSearchLists(advancedSearchViewModel, currentContext);

        return View(advancedSearchViewModel);


Here is some code to save to session in the post:

Session["AdvancedSearchViewModel"] = advancedSearchViewModel;

Note that if you have listboxes (drop down and multi select) you have to rebuild the listboxes in the post method and reselect the selections (for multi select). HTML is stateless. MVC does not send the listbox contents back to the server on the post, it only sends what was selected.