Browse Articles

Intermediate

Changing browser URL with jQuery mobile and Asp.Net MVC

16 Aug 2022
Intermediate
146K Views

Like Asp.Net MVC, jQuery mobile based MVC5 or MVC4 application does not update the browser URL with the current controller or action or id. Since jQuery mobile treats each request as an AJAX request. Hence when you navigate to new page or redirect to new action or page, then the browser URL would be same for all the navigation and redirection.

How to do it..

I did some work around it and found the better solution for changing browser URL with jQuery mobile and Asp.Net MVC. jQuery mobile has data-theme attribute which you need to specify in your DIV having attribute data-role="page"

Make a new MVC Helpers for specifying the data-theme attribute and register it in your web.config of Views folder of your Asp.Net MVC application.

Making Custom Asp.Net Helper

namespace jQueryMobileSite.CustomHelpers
{
public static class CustomHtmlHelper 
{
 public static IHtmlString GetPageUrl(this HtmlHelper 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());
 }
}
}

Adding Custom Asp.Net Helper

<system.web.webPages.razor>
 ...
 <pages pageBaseType="System.Web.Mvc.WebViewPage">
 <namespaces>
 <!-- other code has been removed for clarity -->
 <add namespace="jQueryMobileSite.CustomHelpers"/>
 ...
 </namespaces>
 </pages>
</system.web.webPages.razor>

Using Custom Asp.Net Helper

Now you can use this custom helpers on your views's DIV having attribute data-role="page" . Since this DIV acts as a new page for the jQuery Mobile.

<div data-role="page" data-theme="d" @Html.GetPageUrl(ViewContext)>
@* TO DO: Your Code *@
</div>
What do you think?

I hope you will enjoy this tricks while developing your jQuery Mobile application. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Learn to Crack Your Technical Interview

Accept cookies & close this