-1

I have button onto click,its takes the input values and redirect to another page in javascript which something looks like this window.location = "Action Param1=value1&Param2=Value2". But the method uses query string which i want to avoid. So i thought of using ajax

   ` $.ajax({
            type: "POST",
            url: "/MyController/MyAction",
            data: '{Param1:"value1",Param2:"value2"}',
            contentType: "application/json,charset=utf-8",
            dataType: "json",
            success: function () {
            }
        });`

This does call the controller but does not return anything. I don't know what i am doing wrong here, a working code would be appreciated.

vndpal
  • 697
  • 6
  • 20
  • possible duplicate: https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call – Ahmed Hasn. May 31 '18 at 10:54
  • You could populate a form with the data and set the form's `action` attribute to the page you want to redirect to. Otherwise just post with Ajax and then in the success handler `window.location.href = "the-other-url"` – Reinstate Monica Cellio May 31 '18 at 10:57
  • The whole point of ajax is to stay on the **SAME** page. If you want to redirect DO NOT use ajax! Just make a normal submit and save yourself writing a pointless script –  May 31 '18 at 12:13

1 Answers1

0

if it ony include redirect to the page

return JavaScript("window.location = 'http:yourlink'");

is best option but you want pass the data so do as follows

function redi() {
        var date = new Date(); 
        var link = '@Url.Action("ActionMethod", "Home")';  var args = {
            param1: date.toISOString(),  
            param2: date.toISOString(),
            param3: 'yourdata'
        }; 

        $.ajax({
            type: "GET",
            url: link, 
            data: args, 
            dataType: "json",
            success: function (data) {

                window.location.href = data.redirecturl; 

            },
            error: function (httpRequest, textStatus, errorThrown) {   
                alert("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
            }
        });

}

Controller:

[HttpGet]
    public ActionResult ActionMethod(DateTime param1, DateTime param2, string param3)
    {
        return Json(new { redirecturl = "http:yourlink" }, JsonRequestBehavior.AllowGet);

}
kish
  • 151
  • 3
  • 16