根据datepicker值在控制器中运行方法

我想根据在datepicker中选择的日期在Home Controller中运行方法Index,这是我的View代码:

 $("#calendar").datepicker({ dateFormat: 'dd-mm-yy', onSelect: function (date, instance) { $.ajax({ type: "GET", url: '@Url.Action("Index","Home")/' + date, success: function (data) { if (data.success) { alert(date) } } }) } }).datepicker("setDate", new Date()); 

我想在我的datepicker中选择日期时运行此方法:

  [Route("Home/{date?}")] public ActionResult Index( DateTime? date = null) 

问题是Ajax调用此URL: Home\12-04-2018当我选择12-04-2018而不是/Home/Index/12-04-2018是我的代码错误或我错过了什么? 感谢帮助。

更新您的代码如下,这应该适合您。 日期已作为查询字符串传递

脚本

  $("#calendar").datepicker('setDate', 'today'); $("#calendar") .datepicker({ dateFormat: 'dd/mm/yy' }) .on("changeDate", function (e) { $.ajax({ type: "GET", url: '@Url.Action("Index","Home") + '?date='+ e.date, success: function (data) { if (data.success) { alert(e.date) } } }); }); 

和行动方法:

  [HttpGet] public ActionResult Index( DateTime? date = null) 

更新:

要在视图中更改日期格式,请从C#可以解析的日期对象构建新的日期字符串

 var newDate = e.date.getUTCMonth() + 1 + '/' + e.date.getUTCDate() + '/' + e.date.getUTCFullYear() + ' 00:00:00'; 

并将其作为参数传递给控制器​​。