问题
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)
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.
回答1:
Update your code as below, this should work for you. Date has been passed as query string
Script
$("#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)
}
}
});
});
And action method:
[HttpGet]
public ActionResult Index( DateTime? date = null)
Update:
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.
来源:https://stackoverflow.com/questions/49837216/run-a-method-in-controller-according-to-datepicker-value