开发者

determine when a partialview is going to be rendered as fullview... and hijack the rendering - MVC

So I have this page like this:

....

now I am updating this Comments div using Ajax and all. Now, if the user has javascript disabled, the actionresult "Comments" still ends up returning the partialView except this time it replaces the entire page instead of just div "CommentsDiv". It ruins the formatting of the page, because masterpage is gone. There are a lot of such scenarios throughout the website.

Can I universally specify something like if a partialView is about to be rendered as full view, do something!! (like maybe redirect to a dummy full-page with masterpage only referencing the partialv开发者_StackOverflowiew). Any other approaches?

Note that I simply can't do "IsAjaxRequest",because the very first time the page loads, it won't be an Ajax request, but the actionresult is still supposed to return partialview.


If I have understood your comment about IsAjaxRequest, the first time the page loads, you want the full view, not the partial... But that is pretty much the canonical reason for using IsAjaxRequest.

So all you would need is:

if (Request.IsAjaxRequest)
{
    return View();
}
else
{
   return PartialView("myPartial");
}

The only other scenario I can think of is where you are using a redirect, eg, if implementing the Post Redirect Get pattern. In that case, you can override the OnResultExecuted method in your controller to store the result of IsAjaxRequest in TempData.

That way, when the Get request hits the server, you can check your variable in TempData. If it is empty, then it is an "original" request, so return the full page. Else, it is a redirected request and the original request WAS an Ajax request, and you can return the partial view safely. Ie:

Write a property in your controller as follows:

public bool ImReallyAnAjaxRequest
{
    get
    {
        if (TempData["ImAjax"] == null) return false;
        if (TempData.ContainsKey("ImAjax"))
        {
            return (bool)TempData["ImAjax"];
        }
        else if (Request.IsAjaxRequest())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

Then, write the OnResultExecuted as follows:

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
    if (filterContext.Result is RedirectToRouteResult)
    {
        TempData[keyIsAjaxRequest] = Request.IsAjaxRequest();
    }
}

That way you cover all angles and you can just use the ImReallyAnAjaxRequest everywhere else and know that it will work, whatever the scenario. Or rather, I have used this to build a base WizardController that is completely transparent to Ajax being available or not. A thing of beauty and very dry, especially if packaged into a base controller.

However, I speculate, as your question is not clear.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜