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.
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)
{
...
}