Search code examples
asp.net-mvcredirecttoaction

Send Query String in RedirectToAction MVC


I've two action method in the following controller-

public class VisitMasterController 
{
    public ActionResult StartBrVisit()
    {
        string id=(Request.QueryString["id"].ToString(); //value=null here
    }

    public ActionResult BrNotPresent()
    {
         return RedirectToAction("StartBrVisit","VisitMaster" , new { id = "id", name = "name" });
    }
{ 

After Redirect, Request.QueryString["id"] returns null.

My default route config is-

         context.MapRoute(
         "BR_default",
         "BR/{controller}/{action}/{id}",
         new { action = "Index", id = UrlParameter.Optional },
         new[] { "OpinionLeader.Areas.BR.Controllers" } //add this line
     );

Any help?


Solution

  • You have defined a route with a parameter named id so when you use new { id = "id" }, the RedirectToAction() method finds a match and adds the value as a route value, not a query string value (in the case of name, there is no match, so its value is added as a query string value). You could access it using

    string id = (string)Request.RequestContext.RouteData.Values["id"]
    

    However, it would be far easier to add a parameter to your method

    public ActionResult StartBrVisit(string id)