Since you're doing AJAX requests, we can safely assume that JS is allowed ;)
Thus, use jQuery (or another JS library) to perform the AJAX postbacks, and just post to different urls.
function postTo(url) {
$.post(
url,
$('#theForm').serialize(),
function(returnData) {
// do this on success
}
);
}
Then, just hook up two different calls to this method to your submit links/buttons:
$(function() {
$('#searchButton').click(function() {
postTo('/search/');
});
$('#exportButton').click(function() {
postTo('/export/');
});
});
EDIT in response to follow-up questions in comments:
Q1) How can the controller parse $('#theForm').serialize()
to a ViewModel
object?
A1) This is all part of the ASP.NET MVC model binding, and has nothing to do with the jQuery code. all .serialize()
does with the form is to line up its names and values in a querystring-like format, so that data
on the JSON object will end up something like 'textbox1=first value&textbox2=second value'
etc for all form values. This works the same way as a regular POST request, so ASP.NET MVC doesn't need to handle it any differently than a regular, non-AJAX request.
Q2) Can the controller return entity object and can the callback read it?
A2) You can serialize most objects to JSON using return Json(...)
in your controller, but returning and entity object (which I assume is then from Entity Framework) is not recommended. It is much better to have a data transfer object (DTO) that only has the necessary properties.
As for the callback, the ASP.NET MVC model binders can recognize any object as long as the input data is correctly formatted.