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?

8
  • 1
    in controller Home create method ResultsByCategory that takes id as parameter Commented Sep 5, 2016 at 17:41
  • I have this method. I want to get ID value in my view. Commented Sep 5, 2016 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 Commented Sep 5, 2016 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. Commented Sep 5, 2016 at 17:46
  • I think there is no query string in this url, am i wrong? Commented Sep 5, 2016 at 17:53

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

This code works better for your code

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.