How to make use of an ASP.Net MVC controller action using Ajax to return the difference between two dates in a form?

做~自己de王妃 提交于 2019-12-23 05:38:16

问题


I'm using MVC3 and have a view which is used to book leave for employees. As part of this I want to display the number of days to be taken based on two dates that they enter - I've done this in a rudimentary way using jQuery but want to make use of a controller action I've got which will return a single value based on the two dates (it takes into account weekends and bank holidays).

The question is, what is the best way to pass the values of DateFrom and DateTo (the two inputs) to the controller and retrieve the result using Ajax? I want this value to update whenever either of the dates is changed and without submitting the whole form.

I'm not sure of the best practice for this sort of thing so any help would be appreciated.


回答1:


The question is, what is the best way to pass the values of DateFrom and DateTo (the two inputs) to the controller and retrieve the result using Ajax?

You could subscribe to the change event of those textboxes and send an AJAX request:

$(function() {
    $('#DateFrom, #DateTo').change(function() {
        // whenever the user changes the value send an AJAX request:
        $.ajax({
            url: '@Url.Action("SomeAction", "SomeController")',
            type: 'POST',
            contentType: 'application/json; charset=utf-8', 
            data: JSON.stringify({ 
                dateFrom: $('#DateFrom').val(), 
                dateTo: $('#DateTo').val() 
            }),
            success: function(result) {
                // TODO: The AJAX call succeeded => do something with the results
            }
        });
    });
});

and the controller action could look like this:

public ActionResult SomeAction(DateTime dateFrom, DateTime dateTo)
{
    ...
}


来源:https://stackoverflow.com/questions/5634014/how-to-make-use-of-an-asp-net-mvc-controller-action-using-ajax-to-return-the-dif

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