ASP.Net MVC Quick Introduction

|
| By Webner

ASP.Net MVC Quick Introduction

ASP.Net MVC – In MVC, the architecture of an application is divided into three parts –
Model, View and Controller.

Model – Model represents the shape of data. It is basically used to connect to the database and perform operations on the DB.

View – View is the UI part of the application. This is what a user sees when he visits our application.

Controller – Controller is where all the logic is performed. It accepts the request from the browser, then performs the operations and finally returns the response back to the user.

MVC Architecture
MVC folder structure in the ASP.Net

MVC application contains the following folders –

1. App_Data – This folder is used to contain the local databases.
2. App_Start – This folder is used to contain the files which will run whenever the application will start like Route files, Bundle files etc.
3. Content – This folder is used to contain the static files in our application like css files and images.
4. Controller – This folder has all the controller of our application.
5. Fonts – All the fonts used in the application are stored in this folder
6. Models – All the models of the application are here.
7. Scripts – This folder contains all the scripts files of the application. Bootstrap and jquery script files are here by default.
8. Views – This folder has all the views of the application. Views for a particular controller will be stored in a folder whose name will be same as controller name inside this folder.
9. Global.asax – This file provides a functionality to perform operation on application level like when the app starts, when the session is created or when the action method is executed.

Routing in ASP.net mvc – Routing is used to select the correct action method for the received request. We can configure routes in the RouteConfig.cs files inside the App_Start folder.

Action Selectors –These can be applied on the action methods of any controller. Selectors help the routing engine to select the action for a particular request.

Some Action selectors are –
1. ActionName – We can use this selector to define a different action name than the method name. Ex –

[ActionName("find")]
    public ActionResult GetById(int id)
    {
             return View();
    }

2. NonAction – It shows that the public method of a controller is not an action. Ex –

 
 [NonAction]
    public Student GetStudnet(int id)
    {
        Return View();   
     }

3. Action Verbs – These are used to define the action method with same name but to call them with different request types like one with the get request and another with the post request.
Some action verbs are – GET, POST, PUT, DELETE, PATCH etc.

Razor Syntax – Razor is one of the view engines used by the ASP.NET MVC. It allows us to write HTML and C# or VB together.

Razor view with C# has the file extension of .cshtml.

Inline expression of the Razor view starts with the @ symbol like

<h2>@DateTime.Now.ToShortDateString()</h2>

Multistatement block – We can write the multi statements of the C# code using this –

@{
	C# code…..
}

We can use @: or to display the text inside the code block.

HTML Helpers – HTML helper class helps in generating the HTML elements using the model class object in the Razor view. It also binds the model properties to html elements to bind them and display properties values in the view and also assign the HTML elements values to the model properties.

@Html.ActionLink(“Create New”, “Create”) This will generate the following anchor tag

<a href="/Student/Create">Create New</a>

Validations – We can add validations in our models using the Data Annotations. Data annotations contain different validation rules that can be applied on the Model properties. ASP.NET MVC framework will automatically check these validations and display error messages in the view.

The Data Annotation attributes are included in the System.ComponentModel.DataAnnotations Namespace.

Attribute Description
Required Indicates that the property is a required field
StringLength Defines a maximum length for string field
Range Specifies maximum and minimum value of a numeric field
RegularExpression Used to match the value with a specific Regular Expression
CustomValidation Specified custom validation method to validate the field
EmailAddress Validates with email address format
FileExtension Validates with file extension
MaxLength Specifies maximum length for a string field
MinLength Specifies minimum length for a string field

ViewBag, ViewData and TempData – ViewBag and ViewData are used to pass data from controller to the view but not vice-versa. ViewBag uses dynamic properties whereas ViewData uses the dictionary to pass the data.

Controller – ViewBag.variablename=”value”; ViewData[“keyname”]=”value”

View – @ViewBag.variablename @ViewData[“keyname”]

TempData is used to pass the data from one action method to another action method.

In one action method – TempData[“name”] = “Test data”;
Access in other action method – userName = TempData[“name”].ToString();

public ActionResult Index() {
 TempData["name"] = "Test data";
 TempData["age"] = 30;

 return View();
}

public ActionResult About() {
 string userName;
 int userAge;

 if (TempData.ContainsKey("name"))
  userName = TempData["name"].ToString();

 if (TempData.ContainsKey("age"))
  userAge = int.Parse(TempData["age"].ToString());

 // do something with userName or userAge here 

 return View();
}

These actions can be in the same controller or in two different controllers.

Leave a Reply

Your email address will not be published. Required fields are marked *