MVC 4 Introduction

Introducing ASP.NET MVC 4

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

MVC design pattern




MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.
The MVC framework includes the following components:
·         Models. Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.
In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
·         Views. Views are the components that display the application's user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Product object.
·         Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.


In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input. Writing automated tests for Web Forms-based ASP.NET applications can be complex, because to test an individual page, you must instantiate the page class, all its child controls, and additional dependent classes in the application. Because so many classes are instantiated to run the page, it can be hard to write tests that focus exclusively on individual parts of the application. Tests for Web Forms-based ASP.NET applications can therefore be more difficult to implement than tests in an MVC application. Moreover, tests in a Web Forms-based ASP.NET application require a Web server. The MVC framework decouples the components and makes heavy use of interfaces, which makes it possible to test individual components in isolation from the rest of the framework.


Advantages of an MVC-Based Web Application

The ASP.NET MVC framework offers the following advantages:
·         It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
·         It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
·         It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.
·         It provides better support for test-driven development (TDD).
·         It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

Advantages of a Web Forms-Based Web Application

The Web Forms-based framework offers the following advantages:
·         It supports an event model that preserves state over HTTP, which benefits line-of-business Web application development. The Web Forms-based application provides dozens of events that are supported in hundreds of server controls.
·         It uses a Page Controller pattern that adds functionality to individual pages.
·         It uses view state on server-based forms, which can make managing state information easier.
·         It works well for small teams of Web developers and designers who want to take advantage of the large number of components available for rapid application development.
·         In general, it is less complex for application development, because the components (the Page class, controls, and so on) are tightly integrated and usually require less code than the MVC model.


When you create an ASP.NET MVC Web application project, MVC components are separated based on the project folders shown in the following illustration:



By default, MVC projects include the following folders:
·         App_Data, which is the physical store for data. This folder has the same role as it does in ASP.NET Web sites that use Web Forms pages.
·         Content, which is the recommended location to add content files such as cascading style sheet files, images, and so on. In general, the Content folder is for static files.
·         Controllers, which is the recommended location for controllers. The MVC framework requires the names of all controllers to end with "Controller", such as HomeController, LoginController, or ProductController.
·         Models, which is provided for classes that represent the application model for your MVC Web application. This folder usually includes code that defines objects and that defines the logic for interaction with the data store. Typically, the actual model objects will be in separate class libraries. However, when you create a new application, you might put classes here and then move them into separate class libraries at a later point in the development cycle.
·         Scripts, which is the recommended location for script files that support the application. By default, this folder contains ASP.NET AJAX foundation files and the jQuery library.
·         Views, which is the recommended location for views. Views use ViewPage (.aspx), ViewUserControl (.ascx), and ViewMasterPage (.master) files, in addition to any other files that are related to rendering views. The Views folder contains a folder for each controller; the folder is named with the controller-name prefix. For example, if you have a controller named HomeController, the Views folder contains a folder named Home. By default, when the ASP.NET MVC framework loads a view, it looks for a ViewPage (.aspx) file that has the requested view name in the Views\controllerName folder. By default, there is also a folder named Shared in the Views folder, which does not correspond to any controller. The Shared folder is used for views that are shared across multiple controllers. For example, you can put the Web application's master page in the Shared folder.

In addition to the folders listed previously, an MVC Web application uses code in the Global.asax file to set global URL routing defaults, and it uses the Web.config file to configure the application.

Routes are initialized in the Application_Start method of the Global.asax file. The following example shows a typical Global.asax file that includes default routing logic.

C#
public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = ""// Parameter defaults
        );
 
    }
 
    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}


Understanding the MVC Pattern

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.


Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

1.      MVC model is basically a C# or VB.NET class
2.      A model is accessible by both controller and view
3.      A model can be used to pass data from Controller to view
4.      A view can use model to display data in page.

What is a View?

1.      View is an ASPX page without having a code behind file
2.      All page specific HTML generation and formatting can be done inside view
3.      One can use Inline code (server tags ) to develop dynamic pages
4.      A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
1.      Controller is basically a C# or VB.NET class which inherits system.mvc.controller

2.      Controller is a heart of the entire MVC architecture
3.      Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
4.      Controller can access and use model class to pass data to views
5.       Controller uses ViewData to pass any data to view



MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
·         Root [directory]
o    Controller [directory]
§  Controller CS files
o    Models [directory]
§  Model CS files
o    Views [directory]
§  View aspx/ascx files
o    Global.asax
o    Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:


Browser Request (Step 1)

Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/

Job of Global.asax – MVC routing (Step 2)

The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.

So for [xyz.com]/home/index/:
·         Controller = home
·         Action = index()
·         ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string

Controller and Action methods (Step 3)

MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.

Call to View (Step 4)

Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.
Working with Razor
Many ASP.NET Web pages have C# or VB code blocks in the same place as HTML markup. In some occasions this combination is uncomfortable for writing and delimiting code. To deal with that problem, Razor was designed as an easy to learn, compact and expressive view engine that enables a fluid coding workflow.



Razor is not a new programming language itself, but uses C# or Visual Basic syntax for having code inside a page without ASP.NET delimiter: <%= %>. Razor file extension is ‘cshtml’ for C# language, and ‘vbhtml’ for Visual Basic.


Razor Syntax – The fundamentals


1.      ‘@’ is the magic character that precedes code instructions in the following contexts:

1.      ‘@’ For a single code line/values:
A single code line inside the markup:
cshtml
<p>
   Current time is: @DateTime.Now
</p>
2.      ‘@{ … }’ For code blocks with multiple lines:
cshtml
@{ 
     var name = “John”;
     var nameMessage = "Hello, my name is " + name + " Smith";
} 
3.       ‘@:’ For single plain text to be rendered in the page.
cshtml
@{ 
    @:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day!
}

2.      HTML markup lines can be included at any part of the code:
It is no need to open or close code blocks to write HTML inside a page. If you want to add a code instruction inside HTML, you will need to use ‘@’ before the code:
cshtml
@if(IsPost) { 
     <p>Hello, the time is @DateTime.Now and this page is a postback!</p>
} else { 
     <p>Hello, today is: </p> @DateTime.Now
}
3.      Razor uses code syntax to infer indent:
Razor Parser infers code ending by reading the opening and the closing characters or HTML elements. In consequence, the use of openings “{“ and closings “}” is mandatory, even for single line instructions:
cshtml
// This won’t work in Razor. Content has to be wrapped between { }
if( i < 1 ) int myVar=0;

Conditionals and loops with inline HTML

Here you will find examples of conditionals with inline html.
·         If statement:
cshtml
<p>Single line If</p>
@if(result != ""){
    <p>Result: @result</p>
}
cshtml
<p>Code block If</p>
 
@{
    var showToday = false;
 
    if(showToday){
        @DateTime.Today;
    } else{
        <text>Sorry!</text>
    }
}
·         Foreach statement:

cshtml
<p> Single Line Foreach </p>
<ul>
@foreach (var myItem in Request.ServerVariables){ 
    <li>@myItem</li> 
}
</ul>
cshtml
<p> Code block Foreach </p>
@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}
·         While statement:
cshtml
@{
    var countNum = 0; 
    while (countNum < 50) {
        countNum += 1;
        <p>Line #@countNum: </p>
    }
}

Comments

Comments in Razor are delimited by @**@. If you are inside a C# code block, you can also use // and /* */ comment delimiters.
cshtml
@*
    A Razor Comment
*@
@{
    //A C# comment
    /* A Multi
         line C# comment
    */
}

 Using Essential Tools for MVC

Creating the Example Project

We are going to start by creating a simple example project that we will use throughout this chapter. We created a new Visual Studio project using the ASP.NET MVC 4 Web Applicationtemplate and selected the Empty option to create an MVC project with no initial content. This is the same kind of project that we started with in all the chapters so far, and we called the project for this example EssentialTools.

Using Ninject

We introduced the idea of DI. To recap, the idea is to decouple the components in our MVC applications, and we do this with a combination of interfaces and DI. In the sections that follow, we will explain the problem we deliberately created in the example app and show how to use Ninject, our favorite DI package, can be used to solve it.

Understanding the Problem

In the example app, we have created an example of one kind of problem that DI can solve. Our simple example project relies on tightly-coupled classes: the ShoppingCart class is tightly coupled to the LinqValueCalculator class and the HomeController class is tightly coupled to both ShoppingCart and LinqValueCalculator. This means that if we want to replace theLinqValueCalculator class, we have to locate the change the references in the classes that are tightly-coupled to it. This is not a problem with such a simple project, but it becomes a tedious and error-prone process in a real project, especially if we want to between different calculator implementations, rather than just replace one class with another.

Unit Testing with Visual Studio

There are a lot of .NET unit-testing packages, many of which are open source and freely available. In this book, we are going to use the built-in unit test support that comes with Visual Studio, but there are other .NET unit-test packages are available. The most popular is probably NUnit, but all of the test packages do much the same thing. The reason we have selected the Visual Studio support is that we like the integration with the rest of the IDE, although with Visual Studio 2012, Microsoft has made it possible to integrate third-party testing libraries into the IDE to create a similar experience to the one you get with the built-in test tools.
To demonstrate the Visual Studio unit-test support, we are going to add a new implementation of the IDiscountHelper interface to the example project. Create a new file in the Modelsfolder called MinimumDiscountHelper.cs. 

Using Moq

One of the reasons that we were able to keep our tests so simple in the previous section was because we were testing a single class that depended on no other class to function. Such objects exist in real projects, of course, but you will also need to test objects that cannot function in isolation. In these situations, you need to be able to focus on the class or method you are interested in, so that you are not implicitly testing the classes that are depended on as well.
One useful approach is to use mock objects, which simulator the functionality of real objects from your project, but in a very specific and controlled way. Mock objects let you narrow the focus of your tests so that you only examine the functionality you are interested in.
________________________________________________________________________________

Reach us At: - 0120-4029000; 0120-4029024; 0120-4029025, 0120-4029027; 0120-4029029
Mbl: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com
Description: https://mail.google.com/mail/u/0/images/cleardot.gif


No comments:

Post a Comment