我遇到路由问题。我正在使用下面的 JavaScript 函数向我的 Controller StudentSearch 发送帖子。当我发帖子时,它只传递了第一个参数。该页面为空,这是预期的;但是,开始日期和结束日期都有日期值,但两个参数均为空。我在这里缺少什么?我在网上阅读了文档并进行了搜索,但到目前为止还没有取得任何成功。
//Javascript function
findStudent function()
{
var SearchValue= $("#Search").val();
var StartDate = $('#StartDate').val();
var EndDate = $('#EndDate').val();
var url = '@Url.Action("Search")';
location.href = url + "/" + SearchValue + "/" + StartDate +"/" + EndDate+;
}
//This is the ActionResult in the controller
public ActionResult Search(string SearchValue, string StartDate , string EndDate)
{
//EndDate and STart Date are null here.
}
//the route section in my RouteConfig.cs file
routes.MapRoute(
name: "Search",
url: "StudentSearch/Search/{SearchValue}/{StartDate}/{EndDate}",
defaults: new { controller = "StudentSearch", action = "Search",
SearchValue = UrlParameter.Optional,StartDate=UrlParameter.Optional,
EndDate = UrlParameter.Optional}
);
下午 02:50 更新: 阅读 Chris 评论后,我修改了代码。它没有路由到 StudentSearch Controller 。我得到了一个 404 页面未找到。正如您所看到的,我传入了 Jane 作为搜索值,并传入了 Student1、student2 分别作为开始日期和结束日期(这不是问题,因为参数应该是字符串)。 .../StudentSearch/Search/Jane/student1/student2
最佳答案
不确定您在这里期待什么。 url
变量将解析为字符串 '/StudentSearch/Search'
,因为您为所有路由参数传递空字符串。无论如何,这实际上毫无意义。只需使用 @Url.Action("Search")
即可获得相同的效果。
然后将变量 SearchValue
附加到该字符串,该字符串来自 $('#Search').val()
。就是这样。 StartDate
和 EndDate
从未使用过,尤其是在构造 URL 时。
那么您的路由本身不接受除 SearchValue
作为通配符字符串之外的任何内容。即使您确实将 StartDate
和 EndDate
附加到 URL,所有内容都会进入 SearchValue
参数和实际的 StartDate
和 EndDate
操作参数仍为 null。您的路线需要类似于:
url: "StudentSearch/Search/{SearchValue}/{StartDate}/{EndDate}",
正确填写所有参数。
关于javascript - ASP.NET MVC 4 路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552459/