ASP.NET MVC 4 路由问题

ASP.NET MVC 4 Route Issue

本文关键字:路由 问题 MVC NET ASP      更新时间:2023-09-26

我在路由时遇到问题。我正在使用下面的JavaScript函数向我的控制器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更新:阅读克里斯评论后,我修改了代码。它没有路由到学生搜索控制器。我没有找到 404 页面。如您所见,我分别在 Jane 中传递了搜索值和学生 1,学生 2 用于开始和结束日期(这不是问题,因为参数需要字符串(。...

/学生搜索/搜索/简/学生1/学生2

不确定你在这里期待什么。url变量将解析为字符串'/StudentSearch/Search',因为您要为所有路由参数传递空字符串。无论如何,这实际上毫无意义。只要@Url.Action("Search"),你也会得到同样的结果。

然后将变量SearchValue附加到此字符串,该字符串的形式为 $('#Search').val() .而且,就是这样。 从不使用StartDateEndDate,尤其是在构造 URL 时。

然后,您的路由本身不接受任何内容,只能SearchValue为通配符字符串。即使您确实将StartDateEndDate附加到 URL,所有内容都会进入SearchValue参数,您的实际StartDateEndDate操作参数仍将为 null。您的路线需要如下所示:

url: "StudentSearch/Search/{SearchValue}/{StartDate}/{EndDate}",

正确填写所有参数。