Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 Reload current page with modified querystring values

Background:

I have an MVC layout (master) view which uses @Html.RenderAction to display a dropdown in the left side navigation panel. This dropdown will be displayed on all the pages of the site. The dropdown is wrapped in a form element and on change of the dropdown the form is posted.

Question:

Now, once the form is posted, I need to reload the contents of the current page (whatever page the user is currently on...) with the value of the dropdown attached in the querystring. This would mean replacing the value which might already be there in the querystring from a previous selection.

Example:

  1. The user navigates to the Home page of the website:

Url: /Home/?dropdownvalue=blue

At this point the dropdown displays 'Blue' as selected. The user changes the value in the dropdown to 'Red'. I need to reload the page with the following url -

/Home/?dropdownvalue=red

  1. The user moves to another page in the site:

Url: /CustomerFavorite/?dropdown=red

Change the value in the dropdown from 'Red' to 'Green'.

The 'CustomerFavourite' page should be reloaded with 'Green' in querystring.

I apologize for the lenghty post. But, thought of providing some extra information to clarify the issue.

Thanks.

like image 656
andytech Avatar asked Dec 21 '22 07:12

andytech


1 Answers

Thanks to Darin for providing the link for javascript manipulation of the querystring. But, I wanted a server side solution so here's how I implemented it -

public ActionResult _ColorSelection(ColorModel model)
{
    string selectedColor = model.Color.Value;

    // Modify Querystring params...

    NameValueCollection querystring = 
            HttpUtility.ParseQueryString(Request.UrlReferrer.Query); // Parse QS

    // If Querystring contains the 'color' param, then set it to selected value
    if (!string.IsNullOrEmpty(querystring["color"]))
    {
        querystring["color"] = selectedColor;
    }
    else  // Add color key to querystring
    {
        querystring.Add("color", selectedColor);
    }

    // Create new url
    string url = Request.UrlReferrer.AbsolutePath 
                         + "?" + querystring.ToString();

    return Redirect(url); // redirect

}
like image 180
andytech Avatar answered Mar 23 '23 01:03

andytech