【发布时间】:2012-03-01 17:21:35
【问题描述】:
我需要根据在 MVC 3 的下拉列表中选择的值来重新加载我的页面。 我的下拉列表是这样定义的:
@Html.DropDownListFor(model => model.ID, new SelectList(Model.SchoolBranches, "ID", "Name", Model.ID), new { id = "Branches", name = "Branches"})
到目前为止,我的脚本是这样定义的:
<script type="text/javascript">
$(function () {
$("#Branches").change(function () {
var selected;
selected = $(this).val();
alert(selected);
// make a call to the Index action passing in the 'selected' value to reload the whole page
});
});
</script>
我选择的 ID 工作正常,因为警报会在更改时显示正确的 ID。只是找不到任何示例来说明如何导航回索引操作并发送新 ID。我发现的所有示例都显示部分页面或使用 ajax 进行的此类刷新。我需要重新加载整个页面。
谢谢
更新:
在@Brandon 的帮助下,我尝试了这些方法
<script type="text/javascript">
$(function () {
$("#Branches").change(function () {
var selected;
var url;
selected = $(this).val();
url = '@Url.Action("Index", "School")';
alert(url); //gives /School/Index/55 this is also my current page in my browser address bar
url = '@Url.Action("Index", "School", new {id = ""})';
alert(url); //gives /School
url = '@Url.Action("Index", "School", new {id = ""})' + '/' + selected;
alert(url); //gives /School/41
// window.location = url;
});
});
</script>
这是我在 global.asax 中的路线,这样您就可以看到我没有任何疯狂的路线在进行
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
更新
这行得通:
url = '@Url.Action("NotIndex", "School", new {id = ""})' + '/' + selected;
我获得了正确的新 URL,并且使用所选 ID 触发了操作
【问题讨论】:
-
是否要重新加载 url 中查询字符串中的 ID?
-
@Archer 最初加载页面的控制器上的 Index 操作。
-
@charlietfl 是的,我希望新选择的 ID 成为 URL 的一部分,以导航到操作。该页面位于 /Controller/Index/55 上,其中 55 是上一页中选定项目的 ID。在此页面上,我有一个下拉菜单可以选择不同的 ID,并且需要重新加载页面。
-
@CDSmith,索引是您在路线中列出的默认操作,它会省略操作名称,因为它不需要它。无论如何,该请求都会被路由到索引。您实际上是在使用代码时遇到错误,还是只是没有得到您想要的 URL 字符串?重定向应该仍然有效。
-
@Brandon 是的,遇到错误,我明白了,抱歉,处理您的请求时发生错误。找不到网页。 /School/41 页面不存在。
标签: jquery asp.net-mvc-3