2

I work asp.net MVC, I call an action (let's call it MyAction) from MyController while I'm at the following url www.mywebapp.com/MyController/AnotherAction/123

I need to get the 123 in MyAction, so I started to do something like this :

var url = Request.Url;

In order to parse it then get the ID.

But I'm not sure if it's the "best" way to do it. Do you know how can I get the ID from the current URL when I am in MyAction properly and safely ?

2
  • why you don't create a parameter for your Action to get this data Commented Jul 10, 2014 at 9:46
  • @Arjuna My action is created by an external library, I'm not sure if I can add another parameter and I don't know how to add it with this library Commented Jul 10, 2014 at 9:59

2 Answers 2

9

You can get this from the RouteData:

var url = Url.RequestContext.RouteData.Values["id"];
Sign up to request clarification or add additional context in comments.

Comments

0

you can get the id from URI Like This:


Cotroller:

public ActionResult Index(int id)
    {
//if you want use in view you can save id in view bag
        ViewBag.ID = id;
        Your Code......
        return View(...);
    }

and in view use of view bag

View:

@{  
    ViewBag.Title = "Index";
    var ID = ViewBag.ID;
}

Now you have an ID in the variable

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.