Pages

Men

rh

10/27/2014

ASP.NET MVC 4 - Part [1] - Introduction

Table Of Contents   


Introduction     

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.In this article I will give an introduction to ASP.NET MVC 4 from a beginner’s perspective.
This article is meant for all kind of beginner users who wanted to get started with ASP.NET MVC 4. I have included a small comparison between ASP.NET MVC and ASP.NET Web forms for those who have already explored ASP.NET Web forms 
Currently ASP>NET MVC 4 is supported in Visual Studio 2010 and Visual Studio 2012, previous versions of Visual Studio does not support ASP.NET MVC 4 as of now. If you don’t have ASP.NET MVC 4 in your box then install MVC 4 for Visual Studio 2010 or else use Visual Studio 2012 to get started with this article, You may refer Setup Environment article for more installation details/procedures. 

What is ASP.NET MVC?  

ASP.NET supports three different development models named Web Pages, MVC and Web Forms.
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).
Download from Codeplex.com 

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 Release History   

The Current Version of ASP.NET MVC is 4 and it was released on 15th Aug 2012. ASP.NET MVC 4 is packaged with Visual Studio 2012 and MVC 4 can be installed for Visual Studio 2010. Below I have mentioned the release history of ASP.NET MVC.            
Date Version  
10 Dec 07 ASP.NET MVC CTP 
13 Mar 09  ASP.NET MVC 1.0 
16 Dec 09 ASP.NET MVC 2 RC
04 Feb 10 ASP.NET MVC 2 RC 2
10 Mar 10 ASP.NET MVC 2 
06 Oct 10ASP.NET MVC 3 Beta 
09 Nov 10ASP.NET MVC 3 RC
10 Dec 10ASP.NET MVC 3 RC 2
13 Jan 11ASP.NET MVC 3
20 Sep 11  ASP.NET MVC 4 Developer Preview 
15 Feb 12ASP.NET MVC 4 Beta
31 May 12  ASP.NET MVC 4 RC
15 Aug 12 ASP.NET MVC 4 
In this article we are discussing more about the latest version of MVC, that's MVC 4. Read more from Wikipedia on MVC Release History.  
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.
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 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.  
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. 

Comparing ASP.NET MVC with ASP.NET Web Forms 

If you have already worked with ASP.NET Web forms then you might be interested to see some comparisons between these two.
The main thing is that both ASP.NET Web form and ASP.NET MVC are built on top of ASP.NET Framework. There are some similarities and differences between these two. ASP.NET Web forms web development is very easy compared to ASP.NET MVC apps. and Web forms doesn't require a developer to be an expert in JavaScript and HTML to write a web application but ASP.NET MVC is full of scripting technologies and it requires a good command over scripting technologies. 
ASP.NET Web form is very rich with server controls but in ASP.NET MVC there are no server controls supported and its fully depend on HTML controls. If you look at the below image you can see that no server controls are present in the toolbox. 
There is no View State in ASP.NET MVC. we can use HtmlHelpers in ASP.NET MVC for rendering HTML controls in a view. ASP.NET MVC is based on Separation Of Concerns that's why ASP.NET MVC is pluggable and flexible system. Implementing Test projects with ASP.NET MVC is simple than Web forms. 
ASP.NET MVC request cycle is very simpler than Web forms and MVC gives a good performance. In my opinion I feel for a Web form developer, ASP.NET MVC is difficult to learn and understand as its much into coding not much drag and drop but once its fully understood then its very easy. 
Layout page is the Master page available in ASP.NET MVC and partial views can be considered as a replacement of user control in Web form. Web form uses normal Web-form syntax where as MVC app uses customizable syntax default to Razor.   
There are many more similarities and differences, Once you start writing code with ASP.NET MVC you will learn more.   

Creating an ASP.NET MVC Application – ePhoneBook

In this article all screen shots are based out of Visual Studio 2012 but If you are using Visual Studio 2010 then you will find similar UIs there too.To Create a new MVC 4 application we need to click on 'New Project' menu. 'New Project' menu can be accessed from the start page itself or File->New->Project menu. 
The below given image shows how to create a New Project from start page.  
Creating New Project from File->New->Project. 
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. 
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 
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. 
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. I have written another article on comparison of different view engines.  
Razor is the preferred View Engine for MVC, ASPX View Engine is the legacy View Engine and this option is there for backward compatibility. 
MVC View Engine 
I will be explaining more about Razor on another article.  
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.  
Package.Config File contains the list of the Nuget Package used in this project. 
Now Visual Studio created our project in place and the solution file looks like , 
MVC Web Application 
I have explained the Project Items/ Application folder structure  in another article, before continuing with our newly created project I just wanted to explain the Project Templates.  

Project Templates   

Currently MVC 4 Application in Visual Studio 2010 and Visual Studio 2012 offers 6 different types of project templates. (Previously it was 7 but the final version of MVC 4 doesn't shipped with ASP.NET Single Page Application due to some compatibility) 
I will be explaining the Basic, Empty, Internet Application, Intranet Application, Mobile Application and Web API project templates here.  
Empty  
The Empty template created the minimum references and resources required to run an Asp.net MVC application.As you can see  in below image,  Models, Controllers, App_Data are completely empty folders and View folder only contains web.config and a Global.asax file and web.config.App_Start folder contains 3 configuration files ( FilterConfig.cs, RouteConfige.cs and WebApiConfig.cs ). 
 
This option will be good if you plan to create everything from scratch. 
After comparing the Empty project image and Basic project image we can say that The Basic template is somewhat similar to Empty template. In addition to the Empty project , Content , Script folder are present in this template and Shared folder is present inside Views and also in App_Start folder apart from the three files in empty template, basic template added one more file named BundleConfig.cs (Bundling and minimization).  
Same like Empty Template,this option also good if you plan to create everything from scratch. 
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. 
It's a template used usually to start a normal web project in action. 
The Intranet Application template is same like the Internet Application template, except that it is preconfigured to use Windows-based authentication. 
This template will be a good option if you plan to create an intranet web site. 
The Mobile Application template is another variation of the Internet Application template. This template, however, is optimized for mobile devices and includes the jQuery Mobile JavaScript framework and views that apply the HTML that works best with jQuery Mobile. 
If you plan to target touch based mobile devices then this template is the right option. 
The Web API template is yet another variation of the Internet Application template that includes a preconfigured Web API controller.ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. 
Web API is a great choice for quickly and easily creating data services that your AJAX-enabled applications can easily consume. 
If we want to create a Test project while creating the MVC project itself then we need to mark the Create Unit Test Project Check box. If you don't want to do this at the first time you can add a unit test project later also. 
 
If we are creating MVC Application with Test project then the solution explorer will look like below . 
  

Running our first Application 

  Now we will run our newly created ePhoneBook application. We can run this in debug mode or without debug. To run this go to the Menu Debug->Start Debugging/Start without debugging. 
  F5 - run application 
  You can also use the shortcut key F5 / Ctrl + F5 to run this application 
  The run command is also there in the Standard Toolbar, the below given image shows the run toolbar in VS 2012 IDE. 
  F5 - running web application 
  The below given image shows the run command in standard toolbar of VS 2010 
  F5 - running web application 
  Once you have run the application you can see the below Home page 
  First MVC 4 Web Application 
  If you want to debug your application then you need to set a break-point at the location where you want to hit the debugger. 
  To set breakpoints just go to the menu Debug->Toggle Breakpoint. 
  visual studio - break point 
  You can use the shortcut key F9 also for the same. you might want to note the short keys for Step Into (F11) and Step Over (F10). Once you hit the breakpoint you can resume debugging by pressing F5. 
  To demonstrate the debugging I have placed two breakpoints, one in Home Controller – About() and About.cshtml. When I clicked on About Menu the first break point got hit. 
  
You can Step Over by F10 or just resume to the next breakpoint by F5. I pressed F5 and the second breakpoint got hit.   
  debugging MVC 4 Web Application 
If you want see the value then you can see in watch window and also there are other windows too, to add a object to Watch Window, select the required object and right click and click on AddWatch.   
  Add Watch - visual studio 
  Once you have placed the object in Watch window you can see the current value in that window 
  
  If you resume your breakpoints you can see the About page in action, 
  MVC 4 Url routing 
  Have you noticed that the url is very user friendly with no extensions and all. The ASP.NET MVC routing takes care of this URL routing. Read more on routing on MSDN 
  To stop debugging you need to press Shift + F5 or go to the Debug menu and click on Stop Debugging. 
  stop debugging - visual studio 
  Stopping Debugging from the standard toolbar 
  
  If you want to make any changes while debugging then you can edit and continue the application, if that option is enabled. to check this option is enabled or not, go to Tools->Options then 
   
In ASP.MVC, Layout is used to give similar look and feel for the entire application this was called master page in ASP.NET Web forms. Below given the Layout page in our application,
  
You can see that the Menus like Home, About Contact was shown from this Layout. So how this page is called? So where the content page is placed, it’s simple, the @RenderBody mentioned that the content page will be displayed in that area. 

  Content place holder asp.net mvc layout master page 
  This Layout can be mentioned in individual views or in _viewstart file. The ViewStart file called the Layout in below syntax, 
  
While debugging our application we have noticed something named ViewBag. It's a dynamic data dictionary.
  
As we have used Internet Application Project template the code is generated with Membership management. Let’s have a look into that. 

  Now I’m going to create a User named Shemeer using the Register link.    
  
If you want you can place a breakpoint on AccountController’s register action. When I click ‘Register’ Button it reaches the WebSecurity.CreateUserAndAccount().   
  membership creation mvc 
This method saves my credential to the aspnet* database. Wondering this database was created automatically as part of memebership management and this database by default resides under the App_Datafolder.    
  
And the connection string has been created inside the web.config also   
  aspnet db con str 
Now I'm trying to login using the Login page
  
I’m able to login and my user name is showing in right top corner as logged in   
  

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. I will be publishing a full fledge ePhoneBook on ASP.NET MVC 4 later. This sample code will help you to get more understanding on MVC 4. 
The first thing I’m going to do is adding a PhoneBook Model class .
Adding MVC Model 
I have changed the PhoneBookModel code as below,  
In this class I have mentioned the validation attribute for the elements. The ValidationAttributes are comes fromSystem.ComponentModel.DataAnnotations. There are multiple validation attributes available and all are self-descriptive. 
The above image shows the available validation attributes. Read More on Validation Attribute from MSDN. 
Now let’s add required views (Create, Edit, Delete, Details, List), to add the views just right click on the View folder and click on Add->Views menu. 
Now I’m going to add the Listing view, I have given the View Name as “Index” and selected the 'create a strongly typed view' Model from the Drop-down so that the code will be generated accordingly to the Model. If the created PhoneBookModel is not showing in the dropdown then build the application  and then check. 
select typed model - view mvc 
Now we  can specify which scaffolding template to use so that the code will be generated as per the template , I have selected “List” template like below 
When you click on ‘OK’ button the Index.cshtml is ready. 
The same way I have added all files for this sample project 
 The details page looks like
 
If you look at the code from Create template all validations are in place
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 PhoneBookController. Note that MVC requires the name of all controllers to end with "Controller".
Click on “Add” button to add the controller to our application, now the controller file is created as per our template selection and added to our project, click here to see the generated file
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 
After that I have modified the Created method same as below,
Create Action MVC
If you see this method the return type is ActionResult, What’’s ActionResult. An action result represents a command that the framework will perform on behalf of the action method. The ActionResult class is the base class for action results. It Encapsulates the result of an action method and is used to perform a framework-level operation on behalf of the action method.
  • ContentResult 
  • EmptyResult 
  • FileResult
    • FileContentResult  
    • FilePathResult 
    • FileStreamResult 
  • HttpUnauthorizedResult
    • HttpUnauthorizedResult 
    • HttpNotFoundResult
  • JavaScriptResult 
  • JsonResult  
  • RedirectResult 
  • RedirectToRouteResult 
  • ViewResultBase 
  • PartialViewResult
  • ViewResult  
 Read more from MSDN   
lets come back to our application, The same way I have updated the Edit also 
The above code will return the data for selected entry by the mobile number, Onceyou click on update button in edit page the below method will get called 
For the “Delete” method we don’t have any special User Interface that’s whyonce the entry is deleted we are returning the “Index”view. 
Delete Action MVC
The “Details” method is written as below 
The “Index” page will display the data from the below code 
 
Layout menu mvc
  I have added a menu for Phone Book in _Layout.cshtml. Once this all done let’s “Run” our modified application,  
 When you click on the “Create New” the below page will be shown  
 Edit page looks like below, all validations are working as per the validation attributesin model.     
Summary     
In this article I have explained ASP.NET MVC 4 Intro from a beginner's perspective. I hope you have enjoyed this article and got some value addition to your knowledge. 
I have put my time and efforts on all of my articles, please don't forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles.

Source from :http://www.codeproject.com/Articles/470107/ASP-NET-MVC-4-Part-1-Introduction

No comments :

Post a Comment