Search code examples
c#asp.net-mvcasp.net-mvc-routing

ASP.NET MVC - Extract parameter of an URL


I'm trying to extract the parameters of my URL, something like this.

/Administration/Customer/Edit/1

extract: 1

/Administration/Product/Edit/18?allowed=true

extract: 18?allowed=true

/Administration/Product/Create?allowed=true

extract: ?allowed=true

Someone can help? Thanks!


Solution

  • Update

    RouteData.Values["id"] + Request.Url.Query
    

    Will match all your examples


    It is not entirely clear what you are trying to achieve. MVC passes URL parameters for you through model binding.

    public class CustomerController : Controller {
    
      public ActionResult Edit(int id) {
    
        int customerId = id //the id in the URL
    
        return View();
      }
    
    }
    
    
    public class ProductController : Controller {
    
      public ActionResult Edit(int id, bool allowed) { 
    
        int productId = id; // the id in the URL
        bool isAllowed = allowed  // the ?allowed=true in the URL
    
        return View();
      }
    
    }
    

    Adding a route mapping to your global.asax.cs file before the default will handle the /administration/ part. Or you might want to look into MVC Areas.

    routes.MapRoute(
      "Admin", // Route name
      "Administration/{controller}/{action}/{id}", // URL with parameters
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    

    If it's the raw URL data you are after then you can use one of the various URL and Request properties available in your controller action

    string url = Request.RawUrl;
    string query= Request.Url.Query;
    string isAllowed= Request.QueryString["allowed"];
    

    It sounds like Request.Url.PathAndQuery could be what you want.

    If you want access to the raw posted data you can use

    string isAllowed = Request.Params["allowed"];
    string id = RouteData.Values["id"];