asp.net mvc tutorial for beginner


Hello Friends! : Welcome to my technical blog. In this asp.net MVC tutorial, I will be explaining about basic concepts of asp.net MVC.   

Basics of Asp.net MVC

In software application design, MVC is most widely used architectural pattern that allows us to develop robust applications consisting of three main components (Model, View, Controller) that are loosely coupled, extensible and can be tested independently. MVC is primarily used for web application development.


MVC Architectural Diagram




Model: Holds application data and constraints that acts on the data. The data can be supplied from a service or in some cases it can be user entered data from user interface.

example: CustomerModel that holds customer basic information such as first name, last name, address etc. and constraints like first name cannot be empty, phone number should have minimum 10 digit.

View: is presentation layer or user interface that displays the information or it can accept data from end user via various form elements like textbox, Radio button etc
.
example: customer view displays the customer information. Additionally customer view can provide interface to manipulate data.

Controller: Controller handles incoming user request, performs necessary validations,calls services to update model and finally sends request to the view to render latest information.

example: when customer information is requested, controller takes the request and calls necessary service to load the model and then updates customer view by supplying data from customer model.

                                                                                                            

Advantage of using MVC for application development

Let us go through the prime advantages of mvc and understand how it refines the  application development process. 

Parallel Application development:

As MVC divides application in to 3 main components with each component having its own responsibility.This allows application developer to develop each component independently and tested individually, which promotes parallel development activity.


Impact due to changes are minimal:

Changes in one component will not trigger cascading changes in other components due to loose coupling. Example: let say if we want display the customer phone and email id along with basic information. So all we have to do is update the view, which will not cause any impact on business layer


Test driven development

 MVC supports test driven development. This means we can test each component individually in isolation without relaying on other dependent component.
Example: Controller logic can be tested without waiting for development of view . Or Customer registration logic can be tested without the customer services.


Understanding Internals of Asp.net MVC application

let us create a simple Asp.net application, then we will walk through the application to understand the internals of it. In this article, we will be developing application using Asp.net MVC5 and VS2013. You may use any older or newer version of VS as basic concepts remains the same.

1. Fire up VS2013 and create new project > Asp.net Web Application. (In VS2013 you will see MVC application under Asp.net web application instead of separate MVC application)


New MVC Project


2. Select the template as “MVC”.


MVC Template


Yes, we have setup new MVC4 application in VS now. Note that application separates implementation of 3 components by creating different folder for each one of them



Let us understand each of these component in bit more detail


MVC Controller

Expand the controller’s folder, you will find bunch of controllers. Let us examine HomeController class. It has got 3 public methods, which are called action methods. 

When user requests a webpage, MVC routing engine will decide which controller can serve the request. When decision is made, appropriate controller and action methods are called.  Once the action method performs necessary action, it returns back the response to the user.  The response would be in the form view.

One simple question here would be how action method is mapped to a view? By default, action method will return the view that matches its name. In the below example user requests URL: Home/Index., which gets mapped to Controller: Home and Action method: Index. 


MVC Controller


MVC Action methods

Action methods accepts GET or POST request from the user and performs some actions like validating data, calling service etc. and finally sends response to the user.

Every action method defined in the controller class should qualify following guidelines 

Must be public.
Cannot be a static method.
Cannot be an extension method.
Cannot be a constructor, getter, or setter.
Cannot have open generic types.
Not a method of the controller base class.
Cannot contain ref or out parameters.

The Action methods returns response object of type: ActionResult. Or it can be class derived from ActionResult. Following types of action results are supported.


Action Result
Methods
Description
JsonResult
Json
Returns Json object to the client. This kind of action results are useful when you want to update only some portion of your page through ajax or angularJs
FileResult
File
Returns binary data (video, image files) to clients. For example: User request for file download then action method returns file result instead of action result.
RedirectResult
Redirect
Redirects to another action method using its own URL.
RedirectToResult
RedirectToAction
RedirectToRoute
RedirectToAction:
Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action.
RedirectToRoute:
Redirect to specified root of the application
PartialViewResult
PartialView
This is used for rendering specified partial view with in main view. PartialView updates are used for updating only some portion of  main view
ContentResult
Returns specified content type back to the browser.


Having said that, there is no restrictions on the return type of action methods, since MVC framework allows even string or date time parameter to be sent to browser.  For example: Below method returns string instead of action result.

    public class HomeController : Controller
    {
        public string WhatistheServerTime()
        {
            return DateTime.Now.ToString();
        }
    }


Note: we can prevent a public method from being called by user by decorating action method with [NoAction] attribute.



MVC Models

Models are domain objects that holds data and business rules that act on the data. Data can come through a service or user interface.
For example: Customer registration form within application binds user entered data to Customer Model, which in turn gets validated using business rule that are defined within the Customer model.

MVC Models


   public class CustomerModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailId { get; set; }
        public string PhoneNumber { get; set; }
    }



Data Validation

Any input that comes from user needs be validated at any cost, which is the first step towards securing your application from various security attacks. Best practice is to implement both server side and client side validations. In order do so, we can define data constraints within the model using annotation attributes.

In below example, Required- attribute mandates user to enter input for customer first name and email. Whereas authenticity of the data can be verified using ReqularExpression- attribute.

public class CustomerModel
    {
        [Required(ErrorMessage = "Please enter your First Name",
            AllowEmptyStrings = false)]
        public string FirstName { get; set; }
        public string LastName { get; set; }

        [Required(ErrorMessage = "Email Id cannot be blank", AllowEmptyStrings = false)]
        [RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
            ErrorMessage = "Your email doesnt look good")]
        public string EmailId { get; set; }

        public string PhoneNumber { get; set; }
    }

By defining data constraints on the model, we can enable validations on server side and client side too. 

Understanding MVC View


View: Act as content page that can hold user input fields, display controls and partial view etc. This can be independently rendered in response to a user request. Usually this will be placed within content region of layout View.

Structure of View:The first line within the view defines model or view model to which view is bound. As you know model supplies data to the view and also accepts user entered data from view, which is known as two way binding.
The 2nd line defines title of the page, whereas third line defines layout view that needs be used for this view

@model MVCApplication.Models.CustomerModel
@{
    ViewBag.Title = "Customer";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
Customer View



Partial View

Act as user control that can be placed within a view. These are usually placed under Views/Shared folder of the Mvc Application. Primarily these type of views are used to promote code reusability and avoid code duplication.

 For example: If a blog has section that display’s top 10 trending posts, which needs to be displayed on all blog posts, then we can create partial view for displaying top 10 posts and add it to layout view of the blog.

Structure of Partial view: Structure remains almost same as view. It can be added to a view using following html helper method RenderPartial, which takes partial view name as parameter.

 @Html.RenderPartial("Top10Posts");


Layout view

Act as master page for a mvc application. It contains common controls such as header, Navigation, footer etc. that needs be displayed in every single page of an application. These are usually placed under Views/Shared folder.

Structure of Layout View:Layout view resembles to a basic html page. In addition, it invokes a helper method: RenderBody within the body of the page. RenderBody will load the content of requested view at runtime. So the rendered page will have layout of the layout view and content of requested view.


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
>
<body>
<div class="container body-content">
        @RenderBody()
      
    </div>
</body>
</html>




In this session,we covered following aspects of MVC
  • Basic MVC concepts
  • Internals of MVC application
  • Model and data validation
  • Action methods
  • Structure of view

Jump to the next session to see how we can create simple Asp.net mvc5 application applying above mentioned concepts.

No comments: