根据datepicker值在控制器中运行方法 [英] Run a method in controller according to datepicker value
问题描述
我想根据datepicker中选择的日期在Home Controller中运行Index方法, 这是我的查看代码:
I want run the method Index in the Home Controller according to the date selected in datepicker, Here is my View code:
<input type="text" name="date" class="datepicker" id="calendar" />
$("#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());
我想要在日期选择器中选择一个日期时运行此方法:
I want when I choose a date in my datepicker run this Method:
[Route("Home/{date?}")]
public ActionResult Index( DateTime? date = null)
问题是Ajax将此URL称为:Home\12-04-2018
当我选择12-04-2018而不是/Home/Index/12-04-2018
时,我的代码错误还是我丢失了什么?谢谢你的帮助.
the problem is the Ajax call this URL: Home\12-04-2018
when I choose the 12-04-2018 instead of /Home/Index/12-04-2018
is my code wrong or am I missing something? thanks for help.
推荐答案
按如下所示更新您的代码,这应该对您有用.日期已作为查询字符串传递
Update your code as below, this should work for you. Date has been passed as query string
脚本
$("#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#可以解析的日期对象构建新的日期字符串
To change the date format in view, build new date string from date object that C# can parse
var newDate = e.date.getUTCMonth() + 1 + '/' + e.date.getUTCDate() + '/' + e.date.getUTCFullYear() + ' 00:00:00';
并将其作为参数传递给控制器.
and pass it as parameter to controller.
这篇关于根据datepicker值在控制器中运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!