MVC controller's method not returning view
Solution 1
The redirect in that case has to be done through you AJAX call. Call your action method and do your logic, then redirect on success.
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data} ,
success: function (data) {
window.location.href = "Incidents/Create";
}
})
Solution 2
try:
url:"../Incidents/CreateIncident"
put in $ajax call error handling and see the error, it will help you
$.ajax({
type: "POST",
url: "Incidents/CreateIncident",
dataType: "text",
data: {JsonStr : data},
success: function(result){
// Do stuff
},
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
});
JayL
Updated on June 14, 2022Comments
-
JayL almost 2 years
I tried many ways and it's still not working... I'm calling controller's method with ajax call. Thanks to answer to my previous question it's working fine, I have data that I wanted to send from view in controller (in
CreateIncident
method). Problem is that controller should render new view and redirect to it, but it's not happening. For now I just want to see new view, nothing else, I'll deal with recieved data later. Any idea why is this happening? Is this because I'm calling method with ajax and not by e.g. simpleUrl.AcionLink
?Ajax call to method:
function addMarker(location, fulladdress) { var data = JSON.stringify(fulladdress) + JSON.stringify(location) $.ajax({ type: "POST", url: "Incidents/CreateIncident", dataType: "text", data: {JsonStr : data} }) }
Controller:
public ActionResult Create() { Incident newIncident = new Incident(); newIncident.AddDate = DateTime.Today.Date; newIncident.DateOfIncident = DateTime.Today.Date; newIncident.TimeOfIncident = DateTime.Today.TimeOfDay; return this.View(newIncident); } [HttpPost] public ActionResult CreateIncident(string JsonStr) { // RedirectToAction("Create"); //none of this three is working // return View("Create"); return Redirect("Create"); }
No matter if I'm trying to access
CreateIncident
orCreate
the method is called, but there's no redirect to /Incidents/Create (I'm calling from Home/Index). Any ideas why? I would like to redirect toCreate.cshtml
straight fromCreateIncident
so I wouldn't have to pass data between methods, but any solution will do fine.