Ajax Post and Redirect with Model Value MVC4

2020-07-30 02:51发布

问题:

I am submitting a page through agax post with json data and then redirecting to other view. It's working fine.

 $.ajax({
            url: '/bus/result',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: ko.toJSON(bookingInfo),
            success: function (data, textStatus, xhr) {
                window.location.href = data.redirectToUrl;
            }
        });

MVC Controller

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Result(BusBookingInfo bookingInfo)
        {
            if (Request.IsAjaxRequest())
            {
                return Json(new { redirectToUrl = Url.Action("Booking") });
            }

            //return Redirect("/bus/booking/");
            return RedirectToAction("result");
        }

But now I wanted to pass bookingInfo object to Booking view. I know I can pass through query string but is possible to bind this model object booking view?

回答1:

Instead of window.location.href in success callback,

success: function (data, textStatus, xhr) {
    window.location.href = data.redirectToUrl;
}

You can make another ajax/$.post call here, and pass your object using POST method.

$.ajax({
        url: '/bus/result',
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: ko.toJSON(bookingInfo),
        success: function (data, textStatus, xhr) {
            $.post(data.redirectToUrl, bookingInfo, function(){
               //TODO: callback
            });
        }
    });

Update: Perhaps TempData dictioanry can be helpful here...

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Result(BusBookingInfo bookingInfo)
{
   if (Request.IsAjaxRequest())
   {
     TempData["ViewModelItem"] = bookingInfo;
     return RedirectToAction("Booking");
   }
   //return Redirect("/bus/booking/");
   return RedirectToAction("result");
}        

public ActionResult Booking()
{
   var bookingInfo = (BusBookingInfo)TempData["ViewModelItem"];
   //TODO: code
}