I have an application with a view that contains a form and some ajax code. The ajax code does a POST to send data to my controller. The controller then processes the data.
My question is this: is the controller required to return to the ajax call and then have code in the ajax call to execute on success or error? OR, can the controller execute a RedirectToAction() and return a new view?
For example, my ajax code looks like this:
$.ajax({
type: "POST",
url: "@Url.Action("SaveElectionData")",
dataType: "text",
data: { 'formData': sendData },
success: function (msg) {
$("#Updated").submit();
},
error: function (req, status, error) {
$("form").submit();
}
});
Currently, my /controllername/SaveElectionData action looks like this:
[HttpPost]
public string SaveElectionData(List<FundElection> formData)
{
var returnString = "";
< do all the data processing here >
return returnString;
}
And when the above executes, it should return control to the ajax function where the form should get submitted. This is the definition of the form:
@using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post, new { id = "Updated" }))
{
< form fields here >
}
I dont need to send any of the form fields to the Updated action since the data has already been processed (via the ajax call) so can I change the /controllername/SaveElectionData action to look like this:
[HttpPost]
public ActionResult SaveElectionData(List<FundElection> formData)
{
var returnString = "";
< do all the data processing here >
return RedirectToAction("Updated");
}
In the current state of the application, I am doing this:
1. Render the View
2. Execute the ajax code which sends data to the server for processing
3. Process the data
4. Return to the ajax call
5. Submit the form to the server
6. Render the Updated view
seems like a lot of back and forth between the front and back end.
What I am hoping to do would be this:
1. Render the View
2. Execute the ajax code which sends data to the server for processing
3. Process the data
4. Render the Updated view
Is this valid?
Thanks.