Run a method in controller according to datepicker value

妖精的绣舞 提交于 2019-12-11 05:03:52

问题


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-2018when 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!