akcza
akcza

Reputation: 43

ASP.NET MVC - Get parameter value from URL in the view

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?

Upvotes: 3

Views: 51221

Answers (3)

Olorunfemi Davis
Olorunfemi Davis

Reputation: 1100

This code works better for your code

string id = Request.Path.Value.Split('/').LastOrDefault();

Upvotes: 0

Ali Soltani
Ali Soltani

Reputation: 9936

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();
}

Upvotes: 9

Ravi A.
Ravi A.

Reputation: 2213

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

Upvotes: 8

Related Questions