3

How do I get parameter value from the URL in the client side, view?

URL:

localhost:18652/category/1

MapRoute:

 routes.MapRoute(
     name: "ResultsByCategory",
     url: "category/{id}",
     defaults: new { controller = "Home", action = "ResultsByCategory"}
 );

How do I get ID?

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
akcza
  • 43
  • 1
  • 1
  • 6
  • 1
    in controller Home create method ResultsByCategory that takes id as parameter – derloopkat Sep 05 '16 at 17:41
  • I have this method. I want to get ID value in my view. – akcza Sep 05 '16 at 17:43
  • 1
    there are several options, you can pass it in the model (pass the model when you return the view in ResultsByCategory) or use ViewBag, ViewData or TempData, depending on what you want to do – derloopkat Sep 05 '16 at 17:44
  • I don't want to pass this value from controller to view. I need to get it directly from url, request etc., but in my view. – akcza Sep 05 '16 at 17:46
  • I think there is no query string in this url, am i wrong? – akcza Sep 05 '16 at 17:53
  • Sorry, try Request.Url.ToString(). I believe QueryString only contains parameters. If you split by '/' and get the Last(), this would make the trick. – derloopkat Sep 05 '16 at 18:02
  • This might help you: http://stackoverflow.com/questions/5003953/asp-net-mvc-extract-parameter-of-an-url – Samrat Alamgir Sep 05 '16 at 18:39
  • I think this might help you: http://stackoverflow.com/questions/5003953/asp-net-mvc-extract-parameter-of-an-url – Samrat Alamgir Sep 05 '16 at 18:40

3 Answers3

9

I tested this url:

http://localhost:1865/category/Index/1

In view I have this:

getID

You can get id by this code in example view:

@{
    var id = Request.Url.Segments[3];
}

In general case, You can use this code:

@{
    var id = Request.Url.Segments.Last();
}
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
8

Didn't understand the point of directly getting from URL, Request as your view is always going to get loaded from your controller.

So as derloopkat suggested

In your Home Controller

Public ActionResult ResultsByCategory (int id)
{
  ViewBag.id = id;
  return View();
} 

In your view you can use it by calling

@ViewBag.id
Ravi A.
  • 2,163
  • 2
  • 18
  • 26
0

This code works better for your code

string id = Request.Path.Value.Split('/').LastOrDefault();
Olorunfemi Davis
  • 1,001
  • 10
  • 23