使用模型值MVC4进行Ajax发布和重定向

时间:2013-06-26 08:26:43

标签: jquery asp.net-mvc-4 knockout.js

我通过带有json数据的agax post提交页面,然后重定向到其他视图。它工作正常。

 $.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控制器

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

但现在我想将bookingInfo对象传递给Booking视图。我知道我可以通过查询字符串但是可以绑定这个模型对象预订视图吗?

1 个答案:

答案 0 :(得分:2)

而不是window.location.href成功回调,

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

您可以在此处进行另一次ajax / $.post来电,并使用POST方法传递您的对象。

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

<强>更新 也许TempData dictioanry在这里很有用......

[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
}