javascript - ASP.NET MVC 4 路由问题

标签 javascript asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

我遇到路由问题。我正在使用下面的 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()。就是这样。 StartDateEndDate 从未使用过,尤其是在构造 URL 时。

那么您的路由本身不接受除 SearchValue 作为通配符字符串之外的任何内容。即使您确实将 StartDateEndDate 附加到 URL,所有内容都会进入 SearchValue 参数和实际的 StartDateEndDate 操作参数仍为 null。您的路线需要类似于:

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

正确填写所有参数。

关于javascript - ASP.NET MVC 4 路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552459/

相关文章:

Javascript - 函数工作一次,但再也不会

javascript - Materialise css 模式在页面加载时打开并固定导航 - 不起作用

javascript - 在使用 .replace() 之后,字符串无法选择元素(使用 jquery)

asp.net - 页面生成时间 - ASP.Net MVC

c# - WebApi OData 4,用于在 Controller 中批量插入的第二个 POST 端点

jquery - MVC 4 客户端验证不起作用

javascript - 如何在 AngularJS 的 GridList(动态磁贴)中使用换行符

asp.net-mvc - N次登录失败后如何显示验证码?

c# - 通过 AJAX 传递给 Controller ​​的列表为 null

ASP.NET Web API - 路由