Starting with ASP.NET MVC 4

DotNet

ASP.NET MVC 4 is a framework for building scalable, standards-based web applicationsusing well-established design patterns and the power of ASP.NET and the .NET Framework.
This article is meant for all kind of beginner users who wanted to get started with ASP.NET MVC 4.

What is ASP.NET MVC?
ASP.NET supports three different development models named Web Pages, MVC and Web Forms.
ASPNETTYPES

ASP.NET MVC is a web application development framework built on top of Microsoft’s .NET Framework. ASP.NET Web Form was a replacement for Microsoft’s Active Server Pages (ASP) but ASP.NET MVC is not a replacement for ASP.NET Web Forms and it’s just an alternate way of making an ASP.NET website.

ASP.NET MVC is open source!- In March 2012, Scott Guthrie announced on his blog that Microsoft had released part of their web stack (including ASP.NET MVC, Razor and Web API) under an open source license (Apache License 2.0).

Why MVC?

ASP.NET MVC helps to reduce the complexity of the web application by dividing an application into three layers, Model, View and Controller. This separation (loose coupling) helps in some long term benefits like isolation of components while development and also this separation provides better support for test-driven development (TDD). ASP.NET MVC web site are good in performance and also easy to maintain.

MVC Architecture

The Model-View-Controller (MVC) pattern is an architectural design principle that separates the application components of a Web application into three layers. This separation gives you more control over the individual parts of the application, which lets you more easily develop, modify, and test them.

MVC_Architecture

The Model

Model contains and exposes the properties and application logic In a better way we can say that The model represents core business logic and data. In the ePhoneBook Sample the ‘PhoneBookModel’ class represents the properties of a “Phone Book” in the application and may expose properties such as First Name, Last Name and Mobile Number etc and also it may expose methods.

The View

The View is responsible for creating the response HTML or any responses back to the browser like pdf, html or excel etc. In other way we can sat that the view is responsible for transforming a model or models into a visual representation.

The Controller

Controller is responsible for processing user inputs from view and give responses back to the view. It means that the controller decides the action and performs the tasks/logic based on the parameters.Controller acts as the coordinator between the view and the model.

Creating an ASP.NET MVC Application – MyPhoneBook

The below given image shows how to create a New Project from start page.
1
Creating New Project from File->New->Project.
2
Clicking on New Project menu will show a popup for selecting the required type of Project from the installed templates list. We can create Windows Application or normal ASP.NET Web Application etc using this popup but now we are more interested to create a new ASP.NET MVC 4 Web Application from scratch.
3
Give a proper name for this new MVC 4 application and click ‘OK’ button. I have given ‘ePhoneBook’ name as I’m going to use this project for all my MVC 4 series.

When you click ‘OK’, you’ll be presented with another dialog with Project Templates
4
Select appropriate Project Template (discussed in another section), View Engine and also if you want you can opt for creating a Test Project for this application. You can create a test project later also if you don’t want to do right now. I have selected the Internet Application with Razor View Engine.

What’s a View Engine?

View Engine are responsible for rendering the HTML from your views to the browser. The view engine template will have different syntax for implementation. Currently there are few number of view engines available for MVC and the top four view engines are Razor, traditional ASPX, Spark and NHaml.

Razor is the preferred View Engine for MVC, ASPX View Engine is the legacy View Engine and this option is there for backward compatibility.
ViewEngine

Once you click ‘OK’ after selecting the appropriate project template Visual Studio will create a MVC Web Application project with default files and folders as per the Template Selection.
If look at the visual studio status bar you can see that the project creation progress and the files adding to the project. ASP.NET MVC 4 project template is using Nuget Package Manager to install and manage the assembly references in your application. the below files in status bar adding by Nuget.

Project Templates
Currently MVC 4 Application offers several types of project templates.
In this article we have choosen the Internet Application one.
The Internet Application extends Basic Template with two controllers( Account controller and Home controller) with all the logic and functionality implemented in actions and views. In this template membership management functionality gives the option to user to register and login, change password etc in the website.

Now we will run our newly created MyPhoneBook application. We can run this in debug mode or without debug. To run this go to the Menu Debug->Start Debugging/Start without debugging.

Once you have run the application you can see the below Home page

Untitled

Click on the login part and register an account.
All database will be created!

Modifying our first MVC 4 Web Application

Apart from the generated code I’m just going to add some more pieces to this MVC Web Application.

The first thing I’m going to do is adding a MyPhoneBook Model class .
Here is the code:

using System;
using System.ComponentModel.DataAnnotations;

namespace MyPhoneBook.Models
{
public class MyPhoneBookModel
{
[Required]
[Display(Name = “First Name”)]
public String FirstName { get; set; }
[Required]
[Display(Name = “Last Name”)]
public String LastName { get; set; }
[Required]
[Display(Name = “PhoneNumber”)]
public String PhoneNumber { get; set; }
[Required]
[Display(Name = “Email”)]
public String Email { get; set; }
}
}

Now we have to create the views, it’s really simple:
just create a new folder named “MyPhoneBook” under Views the click “AddView”
Choose a ModelClass and set the one we have just created ( if you don’t see it rebuild your application and retry ).
The create the List,Create,Delete,Edit,Details view according to the operations that we have to perform.

Untitled2

Now we need to add Controller actions for these scaffolding items.
Click on the Add->Controller menu, once you have clicked on that menu then a popup will be shown like below ,

There are multiple controller templates available in this dialogue box
Empty MVC controller
MVC controller with read/write actions and views, using Entity Framework
MVC controller with empty read/write actions
Empty API controller
API controller with read/write actions and views, using Entity Framework
API controller with empty read/write actions

I choosed “MVC controller with empty read/write actions” controller template Now give the controller name as MyPhoneBookController.
Note that MVC requires the name of all controllers to end with “Controller”.

UntitledController

Now I’m going to modify the newly added controller file, the first thing I have added a property that will have a default values for the ePhoneBook:

private static List myPhoneBookList;

public static List MyPhoneBookList
{
get { return myPhoneBookList ?? (myPhoneBookList = new List()); }
set { myPhoneBookList = value; }
}

After that I have modified the Created method same as below:
//
// GET: /MyPhoneBook/

public ActionResult Index()
{
return View(MyPhoneBookList);
}

//
// GET: /MyPhoneBook/Details/5

public ActionResult Details(String number)
{
return View();
}

//
// GET: /MyPhoneBook/Create

public ActionResult Create()
{
return View();
}

//
// POST: /MyPhoneBook/Create

[HttpPost]
public ActionResult Create(MyPhoneBookModel myPhoneBook)
{
MyPhoneBookList.Add(myPhoneBook);
return RedirectToAction(“Index”);
}

//
// GET: /MyPhoneBook/Edit/5

public ActionResult Edit(String number)
{
return View(MyPhoneBookList.FirstOrDefault(x => x.PhoneNumber == number));
}

//
// POST: /MyPhoneBook/Edit/5

[HttpPost]
public ActionResult Edit(String number, MyPhoneBookModel myPhoneBook)
{
myPhoneBookList.Where(x => x.PhoneNumber == number).ToList().ForEach(y => y = myPhoneBook);

return RedirectToAction(“Index”);
}

//
// POST: /MyPhoneBook/Delete/5

[HttpPost]
public ActionResult Delete(String number)
{

myPhoneBookList.RemoveAll(x => x.PhoneNumber == number);
return RedirectToAction(“Index”);

}

Now enjoy yourself by removing the static members and try to save it to db for going on!
Bye!