javascript 将带有 window.location.href 的参数传递给 MVC ActionResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21568186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:12:56  来源:igfitidea点击:

Pass parameter with window.location.href to MVC ActionResult

javascriptjqueryasp.net-mvc

提问by mrshickadance

I'm trying to figure out the best way to do it and have seen a lot of suggestions, but can't get anything to work quite right and would rather do it the best way first.

我试图找出最好的方法来做到这一点,并且已经看到了很多建议,但无法让任何事情完全正确地工作,而宁愿先以最好的方式去做。

Here's the ActionResult on the Controller:

这是控制器上的 ActionResult:

public ActionResult Details(string selectedArtist)
{
    //other code
    return View(selectedArtist)
}

Here's the javascript on the client:

这是客户端上的javascript:

$('#results').on('click', '.item', function () {
        var selectedArtist = $(this).data('artistInfo');
        var selectedId = encodeURIComponent('ARE602H1187FB3B8F8')
        var url = '@Url.Action("Details", "Artist", new { id = "__id__" })';
        window.location.href = url.replace('__id__', selectedId);
    })

Ideally, I would like the pass the selectedArtist object to the controller. It's basically a javascript class that matches a Artist model I have. For now though as a test I am just trying to pass an Id as a string to the controller and can't get it to, it just always comes up as NULL.

理想情况下,我希望将 selectedArtist 对象传递给控制器​​。它基本上是一个与我拥有的 Artist 模型相匹配的 javascript 类。现在虽然作为测试,我只是想将 Id 作为字符串传递给控制器​​,但无法将其传递给控制器​​,但它始终显示为 NULL。

The request that it's building looks pretty good to me ".../Artist/Details/ARE602H1187FB3B8F". However, I'm debugging and the parameter on the controller always ends up NULL.

它正在建造的请求对我来说看起来不错“.../Artist/Details/ARE602H1187FB3B8F”。但是,我正在调试并且控制器上的参数总是以 NULL 结尾。

Am I missing something? And/or is there a better way to do this? Thanks in advance.

我错过了什么吗?和/或有更好的方法来做到这一点吗?提前致谢。

回答by xandercoded

Two options. Update your route table to properly allow the route with its slug"ARE602H1187FB3B8F" to be routed to the applicable action method. Or, you could pass idas a query string parameter, thereby using the default route in your route table:

两种选择。更新您的路由表,以正确允许将带有其slug“ARE602H1187FB3B8F”的路由路由到适用的操作方法。或者,您可以id作为查询字符串参数传递,从而使用路由表中的默认路由:

... Artist/Details?selectedArtist=ARE602H1187FB3B8F