gpt4 book ai didi

javascript - Jquery 或 Javascript 重定向到 Controller /操作

转载 作者:行者123 更新时间:2023-12-01 06:45:01 25 4
gpt4 key购买 nike

我有以下代码,第一次就可以工作:

$("#CompDD").change(function () {
//var parts = (window.location.pathname.split("/"));
var ctrlName = '@ViewContext.RouteData.Values["Controller"].ToString()';
var actnName = '@ViewContext.RouteData.Values["Action"].ToString()';
var url = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//delete ctrlName;
// delete actnName;
//window.location = ($(location).attr('href') + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//window.location = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//$(location).attr('href', url);
window.location.href = url;
//alert(ctrlName + "\n" + actnName);
});

但是,在后续更改相关下拉列表 (#CompDD) 时,它将在链接末尾添加另一个 Controller /操作,例如。它将另一个“Patrons/Index”添加到现有“Patrons/Index”的末尾,然后添加搜索变量等。

请原谅我的代码上的评论和内容。如何让 Jquery(或 javascript)进行重定向,而无需一遍又一遍地附加 Controller 名称和操作名称,或者最好的方法是什么?

编辑:如此简单的修复!我必须将根斜杠添加到 URL 字符串中,示例如下:

var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());

注意我构造的字符串开头的正斜杠......哎呀!

最佳答案

使用 Url.Action 辅助方法构建操作方法的路径。

$("#CompDD").change(function () {

var baseUrl="@Url.Action("Home","Search")";
alert(baseUrl);
// Now append your query string variables to baseUrl
// Ex : baseUrl=baseUrl+"?searchString=testing";
window.location.href=baseUrl;

});

假设您要导航到 Home Controller 中的 search 操作方法。

关于javascript - Jquery 或 Javascript 重定向到 Controller /操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com