jQuery Mobile/MVC: Getting the browser URL to change with RedirectToAction

喜夏-厌秋 提交于 2019-11-27 06:59:00
David Hoffman

I think I've found an answer. Buried deep in the jQuery Mobile documentation, there is information about setting the data-url on the div with data-role="page". When I do this, I get the nice jQuery Mobile AJAX stuff (page loading message, page transitions) AND I get the url in the browser updated correctly.

Essentially, this is how I'm doing it...

[HttpPost]
public ActionResult Products(...)
{
    // ... add products to cart
    TempData["DataUrl"] = "data-url=\"/Cart\"";
    return RedirectToAction("Index", "Cart");
}

Then on my layout page I have this....

<div data-role="page" data-theme="c" @TempData["DataUrl"]>

On my HttpPost actions I now set the TempData["DataUrl"] so for those pages it gets set and is populated on the layout page. "Get" actions don't set the TempData["DataUrl"] so it doesn't get populated on the layout page in those situtations.

The only thing that doesn't quite work with this, is when you right-click... view source... in the browser, the html isn't always for the page you are on, which isn't unusual for AJAX.

Not sure if it is still actual, but in my case I wrote following helper method

public static IHtmlString GetPageUrl<TModel>(this HtmlHelper<TModel> htmlHelper, ViewContext viewContext)
    {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.Append("data-url='");
        urlBuilder.Append(viewContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped));
        urlBuilder.Append("'");
        return htmlHelper.Raw(urlBuilder.ToString());
    }

And then use it as follows:

<div data-role="page" data-theme="d" @Html.GetPageUrl(ViewContext) >

This way I don't need for every redirect action store a TempData. Worked for me fine both for Redirect and RedirectToAction. This would not work properly in case if you use method "View()" inside controller and return different view name, which will change UI, but will retain url.

Hope it helps Artem

David, this was a big help to me. I just wanted to add that in my case I had to use the following format to get the Url to display in the correct form as my other url's:

TempData["DataUrl"] = "data-url=/appName/controller/action";      
return RedirectToAction("action", "controller");

As a side note, I also found that when assigning the value to TempData["DataUrl"] I was able to leave out the escaped quotes and enter it exactly as above and it seems to be working fine for me. Thanks again for your help.

There is an issue on github https://github.com/jquery/jquery-mobile/issues/1571

It has a nice solution without the need of TempData

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!