[英]Jquery or Javascript Redirect to Controller/Action
I have the following code which works on the first time around: 我有以下代码在第一次使用时有效:
$("#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);
});
However on subsequent changes of the drop down in question (#CompDD) it will add another controller/action to the end of the link, ex. 但是,在随后对相关下拉菜单(#CompDD)进行更改时,它将在链接末尾添加另一个控制器/操作,例如。 it adds another "Patrons/Index" to the end of the existing "Patrons/Index", thenit adds the searchsrting variables etc. 它在现有“顾客/索引”的末尾添加另一个“顾客/索引”,thenit添加searchsrting变量等。
Please excuse the comments and stuff on my code. 请原谅我代码中的注释和内容。 How do i get Jquery (or javascript) to redirect without appending the controller name and action names over and over, or whats the best way to do this? 我如何让Jquery(或javascript)重定向,而无需一遍又一遍地添加控制器名称和动作名称,或者什么是最好的方法?
EDIT: Such an easy fix! 编辑:如此简单的修复! I had to add the root slash to the URL string, example this worked: 我必须将根斜杠添加到URL字符串,此示例有效:
var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
Notice the forward slash at the start of the string I construct....Yikes! 注意我构造的字符串开头的正斜杠...。
Use the Url.Action
helper method to build path to action methods. 使用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;
});
Assuming you want to navigate to the search
action method in Home
controller. 假设您要导航到Home
控制器中的search
操作方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.