0

I want to retrieve the value from the URL. My URL looks like:

http://www.test.com/questions/gradename/

http://www.test.com/questions/gradename/subjectname

http://www.test.com/questions/gradename/subjectname/topicname

http://www.test.com/questions/gradename/subjectname/topicname/subtopicname

Now I want to find out the gradename (which is Dynamic value) from the URL.

5
  • @Tim: yes the gradename always on the same position, the domain name not always will be same. Commented Sep 3, 2011 at 7:41
  • Decker97's answer should do the trick for you then. Commented Sep 3, 2011 at 7:45
  • Are you using Asp.Net MVC? If yes you can safely get your parameter inside your controller ('routes'). Every answers to this question looks not so good. You should not manipulate your URL as a simple string Commented Sep 3, 2011 at 7:57
  • @Tim it is not safe - the url is a path to an Action in the code. You defined your route and defined all your possible parameters. Then you can safely get it with the correct method Commented Sep 3, 2011 at 8:01
  • @JohnJohnGa - I don't think he's using MVC - it's tagged as ASP.NET (there's a separate tag for MVC). As long as he's not manipulating the actual URL for some reason, I don't see an issue using either a string (which would not be the same as an URL) or using the Url.Segments - which is a read-only property. Commented Sep 3, 2011 at 8:05

2 Answers 2

3

If you're looking for a server-side / ASP.NET solution, you can use the Segments collection of the Url, e.g:

var gradeName = Request.Url.Segments[2].Trim('/');

Segments is an array of the parts of the URL following the host name, e.g:

[ "/", "questions/", "gradename/", ... ]
Sign up to request clarification or add additional context in comments.

3 Comments

Hostname and / are stripped out, so your first example is correct. I'm not so sure your second one is, though.
Thanks @Tim, that was a typo.
@Tim: Request.Url.Segments[3].Trim('/') 3rd position will return the gradname not 2nd.
2

Regex is pre-optimization. Just split the string on / and take the 4th value.

2 Comments

+1 - I hate it when the obvious stares me in the face and I overlook it. I was thinking string functions but coming up with all sorts of weird ways to do this. :)
By the way - it might be better to say 4th element of the array, as splitting the URL on / will result in at least 5 values, which element 4 being gradename.

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.