Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC controller's method not returning view

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. simple Url.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 or Create 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 to Create.cshtml straight from CreateIncident so I wouldn't have to pass data between methods, but any solution will do fine.

like image 602
JayL Avatar asked Nov 30 '25 03:11

JayL


2 Answers

The redirect in that case has to be done through the 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";
 }
})
like image 157
Moe Avatar answered Dec 01 '25 17:12

Moe


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);
    }
 });
like image 27
Duha Avatar answered Dec 01 '25 17:12

Duha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!