如何在MVC中使用javascript获取可选参数值

时间:2013-04-02 10:36:53

标签: javascript asp.net-mvc-4 parameters

我有以下网址

http://MySite.com/MyGame/Play/1

现在我想使用javascript或jquery获取网址 1 (例如播放后的1)。

我正在使用MVC 4.0 C#应用程序。

3 个答案:

答案 0 :(得分:1)

在JavaScript中,它将是:

var parts = document.location.href.split("/");
var id = parts[parts.length-1];

答案 1 :(得分:1)

var url = document.URL.split('/');

然后你可以做其中任何一个:

var id = url.pop();

var id = url[url.lengh-1];

答案 2 :(得分:0)

如果没有id,Adeel和Jeff的解决方案将失败 - 就像我的情况一样。所以我为我的使用扩展了一点。 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
相关问题