Cant do redirect (ASP.NET MVC)

user7751403

I need to do redirect to controller

Here is my controller

   [HttpPost]
        public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
        {
            QuestionBlock question = new QuestionBlock
            {
                Question1 = question1,
                Question2 = question2,
                Question3 = question3,
                Question4 = question4,
                Question5 = question5,
                Question6 = question6,
                Question7 = question7,
                Question8 = question8,
                Question9 = question9,
                Question10 = question10,
                Interview_Id = id,
            };

            //TempData["id"] = id;
            db.QuestionBlocks.Add(question);
            db.SaveChanges();

             return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);


I try to do it like this

     return RedirectToAction("Index", "Questions", new { id = id });

I have this AJAX call in my View. Maybe trouble in it?

<script>
    $('.click').on('click', function () {
        $('.content').toggle();
    });
    var counter = 0;
  $(document).ready(function () {
        $('#save').click(function () {
            save();
        });
    });
    function save()
    {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                     question1: $('#Question1').val(),
                     question2: $('#Question2').val(),
                     question3: $('#Question3').val(),
                     question4: $('#Question4').val(),
                     question5: $('#Question5').val(),
                     question6: $('#Question6').val(),
                     question7: $('#Question7').val(),
                     question8: $('#Question8').val(),
                     question9: $('#Question9').val(),
                     question10: $('#Question10').val(),

            },
            url: '@Url.Action("Index", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {

                        alert('Вопросы сохранены');




                } else {

                    alert( 'Error'+ da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
}

</script>

But redirection not works. Where is my trouble?

Maybe I need to do it not in controller?

Thank's for help

Shyju

Your current code is returning a JSON response with 2 properties and your main view code is making an ajax call to this action method. So the JSON response returned from the action method will be handled in the success handler of your ajax call. It will not do a redirect unless you explicitly do so.

Even if you replace the return Json with return RedirectToAction, It does not makes sense to use it with the Ajax call. The whole idea of ajaxifying the page is to avoid the traditional page submit - reload experience and replace it with partial page upload behavior (better user experience)

If you absolutely want to redirect to another page, you can do that in the success event handler. But like i mentioned earlier, it does not makes sense to do an ajax post then. Do a normal form post!

if (da.Result === "Success") {
   window.location.href="Give the new Url you want to navigate to here";
}

You can use the UrlHelper class to generate the correct url to the other action method and send that as part of your JSON response.

var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions",new { id= id});
return Json(new { Result = "Success", Message = "Saved Successfully",RedirectUrl=url });

Now in your ajax call , read the RedirectUrl property

if (da.Result === "Success") {
   window.location.href=da.RedirectUrl;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Redirect to HTTPS Error - ASP.NET MVC

Redirect() vs RedirectPermanent() in ASP.NET MVC

Redirect Error in ASP.NET MVC 5

Using javascript to redirect Asp.net MVC

Cant get ASP.NET MVC 6 Controller to return JSON

asp.net mvc6 Authorization redirect do not work when user is not logged

ASP.NET MVC redirect to action Redirect Loops

How can I do a virtual route/redirect based on the path given in ASP.NET VNEXT MVC6?

ASP.NET MVC - How do I Call a Controller Method from within a View to Redirect to Multiple Other Views?

ASP.NET MVC 5 drops trailing period on redirect

Error: redirect_uri_mismatch (ASP.NET MVC)

301 Permanent Redirect in ASP.NET MVC changing url with https

redirect in asp.net mvc 2 controller initialize routine

Redirect to a Controller from class method in ASP.NET MVC

Redirect to error page from ajax call in ASP.net MVC

ASP.NET MVC SqlException does not redirect to error page

Redirect Page based on dropdown information in ASp.NET mvc

jQuery post to controller and redirect to view MVC ASP.net

Redirect to page OnActionExecuting method ASP.NET Core 5 MVC

Redirect to external URI from ASP.NET MVC controller

ASP.NET MVC Redirect Partial View Request If it is not from a View

Asp.net MVC 5 redirect to Account/Login

How to redirect unauthorized users with ASP.NET MVC 6

ASP.NET MVC 3 - Redirect Loop Only on Certain Browsers

Pass message on redirect to view in ASP.NET MVC

Redirect Asp.net Web form to Mvc View vise vars

ASP.NET MVC - Optionally Redirect from a Base Class Method?

ASP.Net MVC identity infinite redirect loop

Could ASP.NET MVC prevent Open Redirect security issue

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive