我有以下第一次使用的代码:
$("#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)的后续更改中,它将在链接的末尾添加另一个控制器/操作,例如。它增加了另一个"赞助人/索引"到现有" Patrons / Index"的末尾,然后添加searchsrting变量等。
请原谅我的代码上的评论和内容。如何让Jquery(或javascript)重定向而不反复添加控制器名称和操作名称,或者最好的方法是什么?
编辑:这么容易解决!我必须将根斜杠添加到URL字符串中,例如,这有效:var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
注意我构造的字符串开头的正斜杠.... Yikes!
答案 0 :(得分:4)
使用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;
});
假设您要导航到search
控制器中的Home
操作方法。