ASP.NET MVC and jQuery with TempData

I have a link in one of my views that users can click, which calls ActionResult. The link looks like this:

<a class="do_something" href="#">lorem ipsum</a>

Then I have javascript that is sent to ActionResult (no data passed to ActionResult) as follows:

$("a.do_something").click(function() {
   var urltopost = "/foo";

   $.post(urltopost);
   return false;
});

ActionResult is designed to then do something:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult foo()
    {
        //do something here

        TempData["Success"] = "You have successfully done something";
        return RedirectToAction("Index", "Home");
    }

What I would like is that when the user clicks on the link, ActionResult does its job and then redirects the user to another view, displaying a TempData message, letting them know that everything is working correctly.

Everything is working fine, except for the redirect part. When a link is clicked, ActionResult is called and does what it should do, but the view is not redirected.

, , - ActionResult? jQuery ( , )?

+3
2

javascript , ( html , ).

html html javascript $.post().

, , :

            var f = $("#FilterProfile");
            var action = f.attr("action");
            var serializedForm = f.serialize();
            $.post(action,
                serializedForm,
                function(data) {
                    $("tbody").html(data);
                });

:

                    $.post("/foo",
                      function(data) {
                          $("html").replaceWith(data);
                      });

, . FF firebug, , $.post().

"" "", $.post() URL- , location.href = data; .

+4

ajax ? ( GET).

<a class="do_something" href='/foo'>lorem ipsum</a>

[AcceptVerbs( HttpVerbs.Get )]
public ActionResult foo()
{
   // do something

   TempData["Success"] = "You have successfully done something";
   return RedirectToAction("Index","Home");
}

, jQuery, , spinner -, , , . , , location.href Url - , html ( ..). , ajax , . .

$("a.do_something").click(function() {
   var urltopost = "/foo";

   $.post(urltopost, null, function() { location.href = "/home"; } );
   return false;
});
+2

Source: https://habr.com/ru/post/1707127/


All Articles