开发者

ASP.NET MVC3: How to redirect to a view when a post was made using AJAX?

I have a search view which uses AJAX to send a request to the server. Depending on the response object returned by the repository, a dialog should be shown (populated with data using a Json object) on the search view (the view from which the request was sent) or the user should be redirected to a results view (populated with data from the response passed as a view model).

开发者_高级运维

Now I have been told (and experienced) that one cannot redirect when a post was made using AJAX. So is there some way to redirect to another view and pass the view model if that response was obtained from the repository and to just post back the Json object if the dialog result should be shown.

My controller action that gets posted to by the search view currently looks somethings like this:

    [HttpPost]
    public ActionResult SomeAction(SearchRequest reqData)
    {
        ResponseBase response = worker.PerformSearch(reqData);

        if (response is ViewResponse)
        {
            //Redirect to "AnotherView" and pass response as the view model.
            return View("AnotherView", response as ViewResponse);
        }
        else if (response is DialogResponse)
        {
            //Return the Json object.
            return Json(new { type = "dialogresponse", data = response });
        }
        else
        {
            //To do: Put error handling code here.
            throw new NotImplementedException();
        }
    }


This question is a bit old, but I thought I would offer my input. I had a similar situation where I had to make a post and either populate some html on the page with update content, or redirect the user to a new location. There are probably better ways to accomplish this however, this is what I did. If you are using jQuery to perform the post it is smart enough to look at the response's content type; to return a view just do as you are now and in the success function populate the content. If you wish to redirect the user

        string javascript = "window.location.href='{0}';";
        return JavaScript(string.Format(javascript, returnUrl));

The mvc framework will attach the javascript mime type to the response, jQuery will pick that up and execute the javascript, and redirect the user. The only catch is the javascript will be populated into the html content in your success method. To overcome this interrogate the content type for html, simmilar to here


I would suggest that you split it into two calls. In the first AJAX call check if it is a ViewResponse or a DialogResponse. If ViewResponse make another AJAX call to get the actual result object else make a non-AJAX server call to redirect to the new view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜