[英]How do get optional parameter value using javascript in MVC
我有以下网址
http://MySite.com/MyGame/Play/1
现在,我想使用javascript或jquery获取URL的ID 1 (例如,播放后为1)。
我正在使用MVC 4.0 C#应用程序。
在JavaScript中,它将是:
var parts = document.location.href.split("/");
var id = parts[parts.length-1];
var url = document.URL.split('/');
然后,您可以执行以下任一操作:
var id = url.pop();
要么
var id = url[url.lengh-1];
如果没有id,Adeel和Jeff的解决方案将失败-就我而言。 因此,我将其扩展了一些用途。 如果有id,则GetIdIfExists函数将返回id。 否则,它将返回null。
编辑:假设id始终是数字。
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function GetIdIfExists() {
var parts = document.location.href.split("/");
var id = parts[parts.length - 1];
if (isNumeric(id)) {
return parseInt(id);
} else {
return null;
}
}
结果:
//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc
> GetIdIfExists()
< null
//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc/0
> GetIdIfExists()
< 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.