How to add ASP.NET MVC to a Web form application

ASP.NET MVC is very popular now a day. But we have much legacy system of ASP.NET web form. If you want to use ASP.NET MVC with legacy ASP.NET web form application. What should you do? This is not encouraged to create an application with ASP.NET web form and ASP.NET MVC together. If you need, you can use. So, let’s start. In this application I used Visual Studio 2012 and .NET framework 4.5

Step 1: Create a ASP.NET Web Forms Application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET Web Forms application, set location and click OK

Step 2: Add Reference
Click right button on the project -> Add Reference ->Extensions -> System.web.mvc
And Add Reference -> Framework -> System.Web.Routing

addref

Step 3: Configure Default Routing
Modify the Application_Start method of Global.asax file. Write down the following code snippet in the Application_Start method .

System.Web.Routing.RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
                new { Controller = "Home", action = "index", id = "" });

Here Route name is Default and default routing is {controller}/{action}/{id} . Here, default controller is Home and default action is index and default id is empty.

Step 4: Create Controller directory and Controller

Create a controller directory by right click on solution ->Add -> New folder -> Controllers
Create a controller by right click on Controller folder -> Add -> Class -> MyController (name of the class)
And create an action in MyController – name AboutMe like below.

MyController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebFormMVC.Controllers
{
    public class MyController : Controller
    {
        public JsonResult AboutMe()
        {
            return Json(new { name = "Mahedee Hasan", designation = "Software Architect"}, JsonRequestBehavior.AllowGet);
        }
    }
}

Now run the application, if you set default page of your application is default.aspx. You will see the output of as usual asp.net webform application. Now change the URL like : http://localhost:53598/My/Aboutme you will see a json output like below. This is actually MVC output.

webmvcoutput

*If you don’t clear in any portion or any suggestion, please leave your comment here. To run the application download required packages.

Retrieving a collection of objects with page methods and AngularJS in ASP.NET Web form

Page Methods are asp.net web form feature. It is an easy way to communicate with the server. You can communicate with server using Page Methods and can do anything you like but mind it is not restful form of communication. In this solution I used visual studio 2012 and bootstrap. So let’s start to retrieve a collection of objects with Page Methods and AngularJS in ASP.NET web forms.

Step 1: Create a ASP.NET Web Forms Application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET Empty web application, set location and click OK

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package AngularJS.Core
PM> Install-Package AngularJS.Resource
PM> Install-Package bootstrap

Step 3: Design Master Page

Add required references for bootstrap and AngularJS and design master page using bootstrap as follows.
You can use theme. For details visit the article “ Easy way to design web layout by bootstrap theme


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebMathodAngular.Site" %>





    

    
    

    
    


    
    

Here you must see that I used the reference of app.js, data.js. studentCtrl.js which are not defined yet. Soon, I will create those files. Another thing that you must set EnablePageMethod=”True”

Step 4: Create Application module, data and angular controller
Create app.js, data.js and studentCtrl.js in scripts -> app folder. Content are given below.

app.js

var app = angular.module('app', ['ngResource']);

data.js

app.value('pageMethods', PageMethods);

app.factory('student', function (pageMethods, $rootScope) {
    var result = [];
    pageMethods.GetStudent(function (data) {
        data.forEach(function (item) {
            result.push({ id: item.Id, name: item.Name, semester: item.Semester, credits: item.Credits});
        });
        $rootScope.$apply();
    });
    return result;
})

studentCtrl.js

app.controller('studentsCtrl', function ($scope, student) {
    $scope.student = student;
});

Here, App.js for just declaring application module, data.js for retrieving data using Page Methods and studentCtrl.js is the main angular controller. You must see, in data.js I have declare pageMethods and call a Page Method name “GetStudent”. This is not yet defines. I will create this method in next Step.

Step 4: Create a Page for View

Create a page name Default.aspx, just right click on the application -> Add -> New item -> Web form using master page. Select Master page and type page name as Default.aspx. Now modify the page as follows.

Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebMathodAngular
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static List GetStudent()
        {
            List lstStudents = new List()
                {
				new Student { Id= 1, Name= "Mahedee Hasan", Semester="5th", Credits= 15},
				new Student { Id= 2, Name= "Robiul Alam", Semester="4th", Credits= 20},
				new Student { Id= 3, Name= "Amit Karmaker", Semester="7th", Credits= 12 },
				new Student { Id= 4, Name= "Zahid Hasan", Semester="8th", Credits= 18},
				new Student { Id= 5, Name= "Shafiqul Islam", Semester="6th", Credits= 15},
				
			};

            return lstStudents;
        }


    }


    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Semester { get; set; }
        public int Credits { get; set; }
    }

}

In Deafult.aspx.cs file, you must see I have created a Page Method which is annoted by WebMethod. This method returns a list of Students object.

Default.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebMathodAngular.Default" %>




    
Id Name Credit Semester
{{student.id}} {{student.name}} {{student.credits}} {{student.semester}}

Look at the page, here I add ng-controller and ng-app and ng-repeat. If you have little idea about angularJs, you must understand the page. Now just run the application and you will get following output.

Output

*If you don’t clear in any portion or any suggestion, please leave your comment here. To run the application download required packages.

Introduction to AngularJs and Bootstrap in ASP.NET Web form

Revolution just arrived. Client side development is getting easier and cheaper. AngularJs is one of the client side development JavaScript framework. It is developed by google. Website designing also get easier due to emerge of bootstrap. Now let’s introduce AngularJS and Bootstrap in a asp.net web form application. Here I used visual studio 2012 as an IDE.

Step 1: Create a ASP.NET Web Forms Application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET Empty web application, set location and click OK

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package AngularJS.Core
PM> Install-Package AngularJS.Resource
PM> Install-Package bootstrap

Step 3: Design Master Page

Add required references for bootstrap and AngularJS , and design master page using bootstrap as follows.
You can use theme. For details visit the article “ Easy way to design web layout by bootstrap theme


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="AngularWeb.Site" %>





    

    
    

    
    


    
    

Here you must see that I used the reference of app.js, data.js. studentCtrl.js which are not defined yet. Soon, I will create those files.

Step 4: Create Application module, data and angular controller
Create app.js, data.js and studentCtrl.js in scripts -> app folder. Content are given below.

app.js

var app = angular.module('app', ['ngResource']);

data.js

app.value('studentInfo', [
  { id: 1, name: 'Mahedee Hasan', credit:20, semester: '8th' },
  { id: 2, name: 'Enamul Haque', credit: 15, semester: '7th' },
  { id: 2, name: 'Arefin Billah', credit: 15, semester: '6th' },
  { id: 3, name: 'Zahid Hasan', credit: 12, semester: '7th' }
]);

studentCtrl.js

app.controller('studentsCtrl', function ($scope, studentInfo) {
    $scope.studentInfo = studentInfo;
});

App.js for just declaring application module, data.js for hardcoded data by javascript and studentCtrl.js is the main angular controller.

Step 4: Create a Page for View

Create a page name Default.aspx, just right click on the application -> Add -> New item -> Web form using master page. Select Master page and type page name as Default.aspx. Now modify the page as follows.


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AngularWeb.Default" %>




 
   
Id Name Credit Semester
{{student.id}} {{student.name}} {{student.credit}} {{student.semester}}

Look at the page, here I add ng-controller and ng-app and ng-repeat. If you have little idea about angularJs, you must understand the code. Now just run the application and you will get following output. Happy programming.

Output

*If you don’t clear in any portion or any suggestion, please leave your comment here. To run the application download required packages.

Easy way to design application layout by bootstrap theme

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine

Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme
Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

download-bootstrap.css

Step 4: Create a Layout page
Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml






    Bootstrap theme test
    
    
    
    



   
    
@RenderBody()

Step 5: Create HomeController and index view
Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Home Page

Step 6: Add Navigation bar

If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml





    Bootstrap theme test
    
    
    
    



    

    
@RenderBody()

Now run the application, you will get a nice layout. Thanks for your patient!

Some other bootstrap theme sites which may help you.

JSON Serialization in ASP.NET MVC and AngularJs

In this article I will show how JSON serialize in ASP.NET MVC and bind data by AngularJs. I will not describe what and how JSON, ASP.NET MVC or AngularJs work. Hope I will discuss these topics in another article.
Let’s start to create an ASP.NET MVC project with AngularJs.

Step 1: Create ASP.NET MVC application

Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine

Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package.


PM> Install-Package jQuery
PM> Install-Package angularjs -Version 1.2.26
PM> Install-Package Newtonsoft.Json

Step 3: Create a layout page
Create a layout page in Views-> Shared ->_Layout.cshtml and add reference of angularjs and jquery.


        
        
        
        Student Information
    
    
        @RenderBody()
    

Step 4: Create a view model “Student” in model folder

public class StudentVM
{
   public int RollNo { get; set; }
   public string StudentName { get; set; }
   public string Class { get; set; }
   public string ClassTeacher { get; set; }
}

Step 5: Create StudentsController
Create StudentsController in Controller folder like following. Here GetSerializedStudentVMS method serialized Student model to JSON.

 
public class StudentsController : Controller
    {
        //
        // GET: /Students/

        public ActionResult Index()
        {
            return View("Index", "", GetSerializedStudentVMS());
        }

        public string GetSerializedStudentVMS()
        {
            var students = new[]
             {
                    new StudentVM {RollNo = 1, StudentName = "Jamal Uddin", Class="One", ClassTeacher="Mr. Anowar Hossain"},
                    new StudentVM {RollNo = 5, StudentName = "Kamal Hossain", Class="Two", ClassTeacher="Mr. Shahana Begum"},
                    new StudentVM {RollNo = 10, StudentName = "Jahid Hasan", Class="Three", ClassTeacher="Mr. Lutfor Rahman"},
                };
          
            //Used to make property name as camel case
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };

           return JsonConvert.SerializeObject(students, Formatting.None, settings); //Returns students list as JSON
        }

    }

Step 6: Create index view
Right click of index action of StudentsController, click view and a view will automatically create to Views-> Students ->index.cshtml

Change the index.cshtml like following

@model string

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Roll No Student Name Class Course Teacher
{{student.rollNo}} {{student.studentName}} {{student.class}} {{student.classTeacher}}

Here ng-init used to initialize the json object and ng-repeat works like foreach.

Step 7: Change RouteConfig.cs
Change RouteConfig like following to run StudentController by default.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Now run the application. Yes you will see the student information in a table. Thanks for your patient 

What is Microsoft Visual Studio?

Microsoft Visual Studio is a wonderful integrated development environment (IDE) from Microsoft. Its user friendly and smart.  It is used to develop computer program for Microsoft windows. It is also used to develop website, web application, web service and web API. Visual studio code editor support intelliSence and code refactoring. It very smart in the world of IDE.

It support many language such as:

C, C++, C#, VB.NET, F#. It also support Phython and Ruby. Support HTML/XHTML, CSS, JavaScript, XML/XSLT
Different version of Visual Studio

Product name Codename Internal
version
Supported .NET
Framework versions
Release date
Visual Studio N/A 4.0 N/A April 1995
Visual Studio 97 Boston 5.0 N/A February 1997
Visual Studio 6.0 Aspen 6.0 N/A June 1998
Visual Studio .NET (2002) Rainier 7.0 1.0 February 13, 2002
Visual Studio .NET 2003 Everett 7.1 1.1 April 24, 2003
Visual Studio 2005 Whidbey 8.0 2.0, 3.0 November 7, 2005
Visual Studio 2008 Orcas 9.0 2.0, 3.0, 3.5 November 19, 2007
Visual Studio 2010 Dev10/Rosario 10.0 2.0, 3.0, 3.5, 4.0 April 12, 2010
Visual Studio 2012 Dev11 11.0 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2 September 12, 2012
Visual Studio 2013 Dev12 12.0 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2 October 17, 2013
Visual Studio “14” CTP 3 N/A N/A N/A August 18, 2014