Question

When I try to add a value in query string collection, I get an error that collection is readonly. Is there anyway of adding a query string from controller class?

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            HttpContext.Request.QueryString.Add("Hello", "World");

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
Was it helpful?

Solution

You can't do this directly from the request as it is a request, not a response. Return a redirect instead of the view:

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

    return Redirect(url); // redirect

This example returns the requested page, but with a constructed query string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top