本文介绍了使用模型值MVC4进行Ajax发布和重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过agax发布提交带有json数据的页面,然后重定向到其他视图.一切正常.

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

[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视图.我知道我可以传递查询字符串,但是可以绑定此模型对象预订视图吗?

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?

推荐答案

代替成功回调中的window.location.href

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

您可以在此处再次调用ajax/$.post,并使用POST方法传递对象.

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

更新:也许TempData的用法在这里可以有所帮助...

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
}

这篇关于使用模型值MVC4进行Ajax发布和重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:11