CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Beginning ASP.NET MVC Framework – PART II

By Gaurav Arora
Posted On Mar 27,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 0
Category: ASP.Net MVC
Print this article.

Beginning ASP.NET MVC Framework – PART II

 

In Part-I we have learnt few basics of the ASP.Net MVC, including features and creation of a sample website in Visual studio. In this entire tutorial we will continue the same with an example.

Introduction

Let’s remind the last tutorial in following steps:

·          The MVC pattern separates the components of an MVC web application, which allows the more controls of the individual parts of that application.

·          MVC pattern separates objects into Model, View and Controllers.

 

·          The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.

Steps to create an ASP.Net MVC application :

·          Start your Visual Studio2008 : Start ->Programs -> Visual Studio2008

·          On the File menu, click New Project.

·          In the upper-right corner, make sure that.NET Framework 3.5 is selected.

·          Under Project types, expand either Visual Basic or Visual C#, and then click Web [I have opted C#]

·          Under Visual Studio installed templates, select ASP.NET MVC Web Application.

·          In the Name box, enter MVCApplicationStepAhead.

·          In the Location box, enter a name for the project folder.

·          If you want the name of the solution to differ from the project name, enter a name for the solution in the Solution Name box.

·          Select Create directory for solution and click OK

 

MVCApplicationStepAhead – At a glance

The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:

·          Content Folder: This folder contains the style sheets. Basically this folder having the responsible files for page layout, design etc.

·          Controller Folder: This folder contains the controller files like AccountController.cs and HomeController.cs

·          Models Folder: Contains Data Model files.

·          Script Folder: Contains Script files.

·          View Folder: For view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an About page view. The Shared folder contains the master page view for the application.

 

 Creating the Routes 

One of the powerful features that ASP.NET MVC brings to the table is the ability to customize the URLs that access your application. The URL routing feature explicitly breaks the connection between physical files on disk and the URL that is used to access a given bit of functionality.   This is important for Search Engine Optimization as well as general usability of the website. 

For example, to access a resource http://localhost/MyStore/ItemDetails.aspx?itemID=1 you can now very give a pretty URL such as http://localhost/MyStore/Ipod

This is done by creating a route table in the global.asax file in the MVC Application. Luckily for us, the defaults included in the template work perfectly this application. Finally, we are ready to start creating application.

 

Scope

Scope of our Test application is,

Creation of an Interface for employees to:

1.      Defining their roles

2.      Getting Roles

 

Our Requirement

·          A Storage where we put records – The Model

·          An Interface where user can interact – The Viewer

·          A media through which all activities could be inspected – The Controller

 

Creation of Model

First of all, as I have discussed we want a container where we store our data. Here, what I mean by container is of-course a Database.

Here are three options for you to choose container of this application:




1.      Go with the existing database file EmployeeDB.mdf under App_data folder of application.

2.      Use the available script EmployeeDB.sql  available under App_data folder of application  to create above database.

3.      Finally, follow bellow mentioned steps to create a new database from / within the environment: 

·          Select  App_data  folder Choose New From File -> New -> File option , or  Right Click the App_data   to add new database file.

·          Create a Database with name  EmployeeDB 

·          Create a Table ERoles, following is the script for this :

 /*******************************************

*This script creates

****** database EmployeeDB

****** Table Roles

********************************************/

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'EmployeeDB')

DROP DATABASE [EmployeeDB]

Go

CREATE DATABASE [EmployeeDB]

GO

 

USE [EmployeeDB]

GO

 

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))

DROP TABLE [dbo].[Roles]

GO

 

/********************************************************************

******This script is a part of ASP.NET MVC-A Step Ahead Series

****** Written by : Gaurav Arora

****** Anyone can use this for educational purposes.

**********************************************************************/

 

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE TABLE [dbo].[Roles](

       [Id] [int] IDENTITY(1,1) NOT NULL,

       [Role] [nvarchar](300) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

       [IsRetiree] [bit] NOT NULL,

       [HireDate] [datetime] NOT NULL,

 CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED

(

       [Id] ASC

)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

GO

 

SET ANSI_NULLS OFF

GO

SET QUOTED_IDENTIFIER OFF

GO

 Fill some initial values into new created table:  

USE [EmployeeDB]

GO

 

INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])

VALUES('Manager - Resource',0,'01/01/2005')

GO

INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])

VALUES('Manager - Technical',0,'01/11/1999')

GO

INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])

VALUES('Member - Technical Staff',0,'01/11/2007')

GO

INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])

VALUES('Sr. Member - Technical Staff',0,'11/11/2007')

GO

INSERT INTO [dbo].[Roles]([Role],[IsRetiree],[HireDate])

VALUES('Lead Member - Technical Staff',1,'11/11/1986')

GO

 

Finally, we have a database with a tablecreated.

To define a Model, there are many tools to generate this task like:

·          LINQ To SQL

·          nHibernate

·          Entity Framework

 

With the invention of LINQ, it’s very easy to solve the some querying problems in applications. I prefer to use LINQ to SQL, although above three are likely to be same but I preferred to use  LINQ to SQL. 

 

To begin,

 

Right click on Models folder and select Add New Item -> LINQ To SQL -> EmpRole.dbml

 

Now, just pick and drop your object of Container i.e.  ERoles  table on  Method Pane.

Alternatively, you can create a new class from tool box by defining all the elements.

Finally, click on ‘Save’ when done.

Many authors say that the next step should be adding the logics but my opinion is you should have at-least one interface to interact user then may go for logics.

So, lets start to create a UI:

Creation of Views

·          Right Click on  Home  folder under  Views  folder to add new Views.

·          Select Add ->  View  Create.aspx, Home.aspx  these are the two views we need here.

·          Now Double click on  Index.aspx and put following lines there:

First include namespace:

<%@ Import Namespace="MVCApplicationStepAhead.Models" %>

 Now, rewrite the above with following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>Employee Roles</title>

</head>

<body>

    <div>

        <h1>

            Employee Roles</h1>

        <ul>

            <%foreach (RoleE roleE in (IEnumerable)ViewData.Model)

              {%>

            <li>

                <%if (roleE.IsRetiree)

                  { %>

                <font color="red">

                    <%= roleE.HireDate.ToShortDateString() %>

                    --

                    <%=  roleE.Role1%>

                </font>

                <%}

                  else

                  { %>

                <a href="/Home/Complete/<%=roleE.Id.ToString() %>"  >Change Role as Retiree</a>

                <%= roleE.HireDate.ToShortDateString() %>

                --

                <%= roleE.Role1 %>

                <% } %>

            </li>

            <% } %>

        </ul>

        <br /><br />

        <a href="/Home/Create">Add New Task</a>

    </div>

</body>

</html>

The above piece of code – just defining the activities of getting Available roles of Employee, adding new roles with Employee, changing Employee current roles.

In  Create.aspx page, we pull some new roles, use following code:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Create.aspx.cs" Inherits="MVCApplicationStepAhead.Views.Home.Create" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <div>

        <h1>

            Add New Role</h1>

        <form method="post" action="/Home/CreateNew">

        <label for="role">

            Role: </label>

        <input type="text" name="role" />

        <br />

        <input type="submit" value="Add Task" />

        </form>

    </div>

</body>

</html>

 

 As you can see, here we are using post method.

 

Creation of Controllers

Click on Controllers folder and add new MVC controller,   named as HomeController.cs

Put the following lines there:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

using MVCApplicationStepAhead.Models;

 

namespace MVCApplicationStepAhead.Controllers

{

    public class HomeController : Controller

    {

        private EmpRoleDataContext dbEmpRole = new EmpRoleDataContext();

 

        //Display a list of Roles

        public ActionResult Index()

        {

            var roles = from r in dbEmpRole.RoleEs   orderby r.HireDate descending select r;

            

            //return View();

            return View(roles.ToList());

        }

 

        //New  Role form

        public ActionResult Create()

        {

            return View();

        }

 

        //Adding new Roles

 

        public ActionResult CreateNew(string roleDescription)

        {

            //New role to database

            RoleE newRole = new RoleE();

            newRole.Role1 = roleDescription;

            newRole.IsRetiree = false;

            newRole.HireDate=DateTime.Now;

 

            dbEmpRole.RoleEs.InsertOnSubmit(newRole);

           

            return RedirectToAction("Index");

        }

 

        //Mark that Role has been Completed

        public ActionResult Complete(int Id)

        {

            //database tasks here

            var roles = fromin dbEmpRole.RoleEs  where r.Id == Id select r;

           

            foreach (RoleE  match in roles)

                match.IsRetiree = true;

 

            dbEmpRole.SubmitChanges();

 

            return RedirectToAction("Index");

        }

 

    }

}

Finally, we reach to conclusion.

Now you can build application or run application:

Start the above application by pressing F5

Add some new roles, change roles to retiree etc.


Downloads

Download Source
Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments