Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  172] [ 2]  / answers: 1 / hits: 19354  / 11 Years ago, sat, november 30, 2013, 12:00:00

I have a ASP.NET website that is URL-Rewriting enabled. I know how to get route parameters using C#:



Page.RouteData.Values[id] as string;


But I don't know how to get it from javascript? Following is my rewritten link format:




http://www.domain.com/topic/{id}/{title}




I want to get this {id} field using JavaScript. Please help!



UPDATE



I have this code that gets request parameter.



function getParameterByName(name) {
name = name.replace(/[[]/, \[).replace(/[]]/, \]);
var regex = new RegExp([\?&] + name + =([^&#]*)),
results = regex.exec(location.search);
return results == null ? : decodeURIComponent(results[1].replace(/+/g, ));
}


How can this be modified to get route parameter?


More From » c#

 Answers
2
function getValueAtIndex(index){
var str = "http://www.sample.com/234/Fiddle/test"; //window.location.href;
return str.split("/")[index];
}
console.log(getValueAtIndex(3));

Update


Here's a much cleaner way of getting value at an index in the route using plain JS:


    location.pathname.split('/')[index]


For example, for the current page,


location.pathname = '/questions/20302776/how-to-get-route-parameter'

You can get the question id by doing:


location.pathname.split('/')[2]

// Notice that the index does not start from zero.

[#73977] Thursday, November 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;