Use jQuery Mobile MVC to Build Mobile Based Application in Asp.Net MVC

  Total Views : 1761
  Comments : 0
 
  Keywords : How to build asp.net mvc application specific to mobile views, Asp.net mvc build responsive web site using jquery mobile mvc nuget package, Build mobile site in asp.net mvc with example

Here we will learn how to implement mobile sites in asp.net mvc using jQuery mobile mvc or mobile specific views for website in asp.net mvc using jquery mobile mvc nuget package. In today fast growing world people are having different devices such as Desktop, Mobile phone, tablet, phablet, Smart TV. In these devices may have different operating system but internet is common to acess all devices. If we want to create a native application for all these devices may cost more than just creating a mobile base website and website can be viewed for all different devices browsers.

 

Most important meta tag that helps adaptive rendering our site is viewport Meta tag. If you open any desktop site on your mobile it is so large that you need to scroll enter page to see it and text for reading is so small that can’t be read properly. The viewport help us to render page according to mobile size in order to define viewport, we need to add a viewport Meta tag in <head> section of your HTML page like as shown below

 

<meta name="viewport" content="width=device-width"/>

Following are the properties of meta tag

 

Property

Description

width

The width of the virtual viewport of the device.

device-width

The physical width of the device's screen.

height

The height of the "virtual viewport" of the device.

device-height

The physical height of the device's screen.

initial-scale

The initial zoom when visiting the page. 1.0 does not zoom.

minimum-scale

The minimum amount the visitor can zoom on the page. 1.0 does not zoom.

maximum-scale

The maximum amount the visitor can zoom on the page. 1.0 does not zoom.

user-scalable

Allows the device to zoom in and out. Values are yes or no.

 

 Follwing are the different devices available in today and we need to make application compatible with all devices

 

Different Devices Available in Today's world

 

For building mobile base application ASP.NET framework has built in support. Asp.net mvc has “Mobile Application” template which can be use to develop only mobile based Web Application. If we want to develop site for (desktop and mobile) then we are going develop desktop edition first after that we will modify site to work for mobile also by using “Install-package jQuery.Mobile.MVC”. 

 

If we try to implement mobile site then it’s not possible because user will access site through mobile as well as desktop at that time your site might break (will not look proper) for that let's begin with creating a site using Internet application template in MVC. Let’s start with creating MVC internet application for desktop and mobile both.

Create New Asp.Net MVC Application

Let's start with creating new asp.net mvc application for both desktop and mobile for that Open visual studio studio à Go to File à Select New à Select Project

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up for selecting your Template and Project type. From Templates select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application and here we are giving name as “TutorialMobilesite” then finally click on OK button

 

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Internet Application template and set view engine as Razor and we are not going to create Unit testing for this project hence do not check this option and finally click OK button like as shown below

 

select internet application template for asp.net mvc mobile mvc project

 

After selecting all options as discussed above now click OK button our Project will be create like as shown below

 

Asp.Net MVC Implement responsive website using jQuery Mobile MVC Nuget Package

 

After completion of displaying project structure now let’s run our application which we created that will be like as shown below

 

asp.net mvc application home page

 

It’s working fine now in desktop view. Let’s start with creating new Model, Controller, and View for creating new forms and we are going to view it in desktop and mobile.

Adding New Model in Asp.Net MVC (OrderModel)

For adding model in solution explorer just right click on Model folder and select Add then inside that select Class and then Name class as OrderModel and finally click on Add button to create Model.

 

Add new model file in asp.net mvc mobile responsive website example

 

Now give name to class file as "OrderModel" and click Add button like as shown below.

 

Give name to new model class in asp.net mvc responsive mobile website

 

After creating OrderModel class it create in Model folder. Now inside OrderModel class we are going add some properties.

 

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

 

namespace TutorialMobilesite.Models

{

public class OrderModel

{

[Key]

public int OrderID { get; set; }

[Required(ErrorMessage = "Enter Order Name")]

public string OrderName { get; set; }

[Required(ErrorMessage = "Enter Order Price")]

public int? OrderPrice { get; set; }

[Required(ErrorMessage = "Enter Order Date")]

public DateTime? OrderDate { get; set; }

}

}

After adding Countries Model now we are going to use Code First Approach for accessing database for that we are going to add class DbconnectionContext which will be inheriting from DbContext.

Adding New Context class in Asp.Net MVC

For adding context class In Solution Explorer, right click the Models folder à Select Add à then select Class once click class new dialog will popup in that name the class DbconnectionContext and click Add once we add content file that will be like as shown below.

 

after adding dbcontext class file in models folder in asp.net mvc application

 

Now open DbconnectionContext file we will see a simple class with name DbconnectionContext now just inherit from DbContext Class after this step in DbconnectionContext Constructor we are going call base class (DbconnectionContext) and provide connection string in it.

 

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace TutorialMobilesite.Models

{

public class DbconnectionContext : DbContext

{

public DbconnectionContext()

: base("DefaultConnection")

{

 

}

public DbSet<OrderModel> OrderModel { get; set; }

}

}

Nowe we will add connection string in web.config file because we need to tell it where to create Database.

 

<connectionStrings>

<add name="DefaultConnectionproviderName="System.Data.SqlClientconnectionString="data source=SAI-PC; initial catalog=OrderDB1; persist security info=True; user id=sa; password=Pass$123; App=EntityFramework" />

</connectionStrings>

After completion of database part now let’s move towards adding Controller.

Adding New Controller in Asp.Net MVC

To add controller just right click on Controller folder then select Add from list and inside that select controller like as shown below.

 

Add new controller in asp.net mvc mobile application

 

After selecting controller a new dialog will pop up with name Add Controller. In that metion name as "OrderController". In template we are going to select MVC controller with read/write actions and views, using Entity Framework and in model class we are going to select OrderModel which we created earlier and select data context class as DbconnectionContext.

 

Finally click on Add button to create OrderController. After clicking on Add button scaffolding will generate all action method and code for insert, update, delete along with all view regarding to Action Method.

 

Give name to controller and select mvc controller with read write actions and other options in asp.net mvc

 

Following is the snapshot how our Controller will look like after Using scaffolding technique.

 

Asp.net mvc controller structure after selecting scaffold template

 

In view folder look at Order view for the files which are generated.

 

Views folder structure in asp.net mvc mobile application

 

Now save and run your application to check we are going to access index page of order contoller to check how it's design look like in browser.

 

Index page output in asp.net mvc mobile site

 

If you look same page in mobile it will not look proper. To view in mobile download [Opera Mobile Emulator] from given link and install http://www.opera.com/de/developer/mobile-emulator. After installing Opera Mobile Emulator here is view how it look like and at right hand side of Profile there are list of Mobile phone names avaiable from that select any one and test you can also add new phones in to this Emulator.

 

After installing Opera Mobile Emulator

 

Now open index page of application on the phone it won't look proper.

 

Asp.net mvc index page view in mobile view

 

Now design application to work in Mobile let's Install jQuery.Mobile.MVC Package from NuGet commands like as shown below.

 

Installing jquery mobile mvc nuget package in asp.net mvc application

 

After installing it will open a text file to say add BundleMobileConfig.RegisterBundles(BundleTable.Bundles); to Application_Start() in global.asax file. Now open Global.asax file and add BundleMobileConfig to Application_Start Method like as shown below.

 

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

BundleMobileConfig.RegisterBundles(BundleTable.Bundles);

AuthConfig.RegisterAuth();

}

}

After installing jQuery.Mobile.MVC package following are the files (_Layout.Mobile.cshtml , _ViewSwitcher.cshtml) which added inside shared folder. By view switcher user can switch from mobile view to desktop view and desktop view to mobile view.

 

View switcher in asp.net mvc application after installing jquery mobile mvc

Now save and run application and test in opera Mobile Emulator. If check in Opera Mobile Emulator view has changed a bit.

 

Asp.net mvc application view in opera mobile emulator

 

Now if we click on Create New Button on this page it give Error like as shown below.

 

Server error in asp.net mvc application while viewing in opera mobile emulator

 

To resolve this Error just Remove or Comment this bit of code which is given below.

 

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}

Wow it looks good now we don't required to write lots of code for doing this stuff to view in Mobile all of this part will be handled by jQuery.Mobile.MVC package.

 

Crete Order details page in asp.net mvc mobile view

Adding Display Mode Provider in Asp.Net MVC

After this if we check similar website in Windows OS or Iphone device it will look different for handling that we are going to se Display Modes to display view based on mobile it requested for it. E.g. if user requested from Android phone then Android phone View must only display and in same way if he is requesting website from Iphone then Iphone phone view must only display same to Windows. We are going to add DisplayModeProvider in Global.asax file like as shown below.

 

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("WP")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("Windows Phone OS", StringComparison.OrdinalIgnoreCase) > 0)

});

 

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) > 0)

});

 

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("Android")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("Android", StringComparison.OrdinalIgnoreCase) > 0)

});

Following is the complete code of Global.aspx file after adding bundle config and display mode.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

using System.Web.Mvc;

using System.Web.Optimization;

using System.Web.Routing;

using System.Web.WebPages;

 

namespace TutorialMobilesite

{

// Note: For instructions on enabling IIS6 or IIS7 classic mode,

// visit http://go.microsoft.com/?LinkId=9394801

 

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

BundleMobileConfig.RegisterBundles(BundleTable.Bundles);

AuthConfig.RegisterAuth();

 

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("WP")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("Windows Phone OS", StringComparison.OrdinalIgnoreCase) > 0)

});

 

DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("iPhone")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) > 0)

});

 

DisplayModeProvider.Instance.Modes.Insert (1, new DefaultDisplayMode("Android")

{

ContextCondition = (ctx => ctx.GetOverriddenUserAgent()

.IndexOf("Android", StringComparison.OrdinalIgnoreCase) > 0)

});

}

}

}

Add View According to Mobile Devices in Asp.Net MVC

After adding Display Mode provider to Global.asax now let’s add view in Views Folder according to DefaultDisplayMode [WP, Iphone, Android].

 

We are going to add Android view first just copy Create.cshtml file from order folder in inside view and paste in same folder the name of view changes after pasting in folder [Copy of Create.cshtml]. Now we are going to rename this file to [Create.Android.cshtml]. In same way we have to do for windows phone and Iphone.

 

Following is the image which shows our modes for windows, androdi and iphone [Create.Android.cshtml], [Create.WP.cshtml], [Create.iPhone.cshtml]

 

After adding all mobile software views in asp.net mvc

 

Now we have four views to display one for Desktop and other are for different Mobiles. Now just change header name of page in all view with their device name such that it can be easy to recognize. For e.g <h2>Iphone</h2>

Adding Mobile/Responsive Web Design Tester for Testing Mobile Views.

For testing in Iphone and Windows we have extension in chrome that will help us to do this. Just open chrome browser and from Menu select more tool inside that select extension then in search box enter “mobile testing” and from list select Mobile/Responsive web Design Tester and add this extension to chrome.

 

Adding mobile testing extensions in google chrome

 

After adding it gets added to right corner of your browser window. Inside that there is complete list of mobile we can test like as shown below.

 

Complete Mobiles list in Google Chrome to test asp.net mvc mobile application

 

If we run application in desktop our view will be like as shown below.

 

Asp.net mvc application view in desktop

 

To test website in mobile just open page in browser which you want to test and then from [Mobile/RWD Tester] select phone for which you want to test we are first going to test android and Iphone that will be like as shown below.

 

select devices to test asp.net mvc web application in mobile tester

While testing in [Mobile/RWD Tester] we selected Galaxy S6 phone which is an Android phone for that an Android view has been popup and in similar way we selected Iphone 4 phone from [Mobile/RWD Tester] for that an Iphone view has been popup. Following is the output render for both device view.

 

Android and Iphone mobile view of asp.net mvc application

 

This is the magic which is done by JQuery.mobile.MVC package in asp.net mvc applications.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User