3

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.

6
  • 3
    If you need to navigate (redirect) then AJAX is the wrong tool -- Just use a simple form post. If you want the AJAX solution to work you'll need to redirect with JavaScript in the success handler. Commented Jan 6, 2016 at 19:01
  • I thought about form, but I'm sending data from JavaScript and I had problems with putting data from JS to form, so I went further with that solution. Cause finally I want to view with form which would be partially filled by data that I sent. Commented Jan 6, 2016 at 19:04
  • As Jasen said, you have to do redirect from JS or use a form. Filling and submitting form through js shouldn't be a problem. Commented Jan 6, 2016 at 19:18
  • So, any hints how to fill html form in view handled by another controller? I have to somehow fill form in first view, send it to controller and there render new view with data I recieved? Or can I directly fill form in another view (and another controller, as a reminder) with JS? Commented Jan 6, 2016 at 19:28
  • This is a case where you are trying to use a wrong tool for a right purpose. Either you have to forget about javascript and do it in mvc style or, you have to adopt javascript fully. Commented Jan 6, 2016 at 21:25

4 Answers 4

5

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";
 }
})
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, as for redirection, it's working. But that way I can't (or I don't know how?) see data that I'm sending. I'm trying to create object of model, put it there and pass this object to view by return View(object), so I can see data in form, but the form is empty.
Moe is right. Your action should return (i.e.) json data indicating success or failure of action. Additionally You can return redirect url, but redirection itself must be done using javascript inside "success" event
@JayL, This is not how you pass the data if you want to redirect to another action method. Save your object somewhere (DB for instance) pass the ID to the new action method, get the data and display it. In the above ajax call, you can pass the id when you redirect. "/Incidents/Create/1".
Ok, so right now I should 1) Save data to DB in CreateIncident 2) After success redirect to Create View with Ajax 3) On loading Create View access DB and fill form with previously saved data. That's correct? Problem is that when user finally decide not to save incident I have trash in DB that needs to be removed, that's why I wanted to save data to DB only if user press save button later on form.
You lost me buddy :d If you don't want to create an incident, then why do you need to pass the data? why don't you just redirect the user directly to the create? am i missing something? If you want to pass only two / three parameters then you could use a query string if the data you are passing is not sensitive.
|
1

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);
    }
 });

4 Comments

If there's an error thrown, where can I see it? About url, nothing changed. Call is (and was) made and it's ok, method is running. In Firebug I can see POST CreateIncident and GET Create with code as above, but I'm still on Home/Index view.
check my updated answer, you can see error as alert if there error, you can put alert on success to know if it sussess, but break point in ur action o show if ajax call ur methood
I tried your way and with .done( function() {...}) at the end of call with window.location.href = "../Incidents/Create" inside. I'm redirected to proper view, but it's empty, even though in method I have return View(model). I'm loosing data sent by ajax.
I miss thing do your action reach your action ? if you put break point it stop in your action??? if yes ->try to return partial view , and in success :function(result) replace the result on div. or you can use ajax by using ajax link helper in your home page , you don't need to make ajax call using javascript
0

Use the view's full path instead of its name.

return View("/Incidents/Create");

Comments

0

Yes redirecting page in success event of ajax call is the only solution, as you are making ajax call not submitting a form. Browser redirects automatically after post only if you are posting a form.

However you can use following code if you don't want to redirect it in success event.

function postData(url, allData){
    form = document.createElement('form');
    for(data in allData)
    {
        var input = document.createElement('input');
        input.type = 'text';
        input.name = data;
        input.value = allData[data].toString();
        form.appendChild(input);
    }
    form.method = 'post';
    form.action = url;
    form.submit();
}

and use this function like this :

function addMarker(location, fulladdress) {
    var data = JSON.stringify(fulladdress) + JSON.stringify(location);
    postData('/Incidents/CreateIncident', {JsonStr : data})
}

warning : haven't tested :).

6 Comments

Well, this isn't working either. Functions are called, but there's no redirection, also CreateIncident action isn't called.
It's working man. Just open your console right here. Past function in console and call it. It is redirecting.
I don't know, I copy-pasted code you wrote. addMarker is called, postData is called, but CreateIncident isn't. There's no sign of call when I check in Firebug in network section. I set breakpoint in CreateIncident and it wasn't hit. I'm really not familiar with JS, so maybe I'm making some simple mistake. Also, how should I call it in console? I'm getting undefined when I'm trying to call it with parameters.
Okey then change url from Incidents/CreateIncident to /Incidents/CreateIncident. I have updated the code can you please check it again?
Calling in console meanse firegug's console panel or if you are using google chrome then press F12 and you will be able to see console panel.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.