Introduction of Asp.net MVC Basics for beginners

MVC is an architectural pattern which separates the representation and user interaction.
It's divided into three broader sections,

  1. Model
  2. View
  3. Controller. 

Below is how each one of them handles the task.
View : The View is responsible for the look and feel.
Model: Model represents the real world object and provides data to the View.
Controller: The Controller is responsible for taking the end user request and loading the appropriate Model and View.

Advantages of ASP.NET MVC


  1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
  2. Complex applications can be easily managed
  3. Separation of concerns. Different aspects of the application can be divided into Model, View and Controller.
  4. ASP.NET MVC views are light weight, as they do not use view-state.
  5. It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).
  6. Support for existing ASP.NET features like membership and roles, authentication and authorization, provider model and caching etc.
  7. It's an extensible as well as pluggable framework. We can plug components and further customize them easily.
Advantages of MVC over ASP.NET


Following are advantages of MVC over ASP.NET
  1. Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller). 
  2. Easy to UNIT Test. 
  3. Improved reusability of model and views. We can have multiple views which can point to the same model and vice versa. 
  4. Improved structuring of the code.
Namespace classes used in ASP.NET MVC

-All the namespaces and classes used for ASP.NET MVC reside in the System.Web.Mvc assembly.


-System.Web.Mvc namespace
This namespace provides classes and interfaces that support the MVC pattern for ASP.NET Web applications.
This namespace also contains classes that manage controllers, controller factories, partial views, action results, views and model binders.


-System.Web.Mvc.Ajax namespace
This namespace provides classes that support Ajax scripts in an ASP.NET MVC application.
The namespace also provides support of Ajax scripts and Ajax option settings.


-System.Web.Mvc.Async namespace 
This namespace provides classes and interfaces that support asynchronous actions in an ASP.NET MVC application.


-System.Web.Mvc.Html namespace 
This namespace provides classes that help in rendering HTML controls in an MVC application.
The namespace contains classes providing forms, input controls, links, partial views, and validation support


Different return types of a controller action method

The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.

  1. ViewResult
  2. JavaScriptResult
  3. RedirectResult
  4. ContentResult
  5. JsonResult
Methods used to render the views in ASP.Net MVC

Below are the methods used to render the views from action - 

View() : To return the view from action.
PartialView() : To return the partial view from action.
RedirectToAction() : To Redirect to different action which can be in same controller or in different controller.
Redirect() : Similar to "Response.Redirect()" in webforms, used to redirect to specified URL.
RedirectToRoute() : Redirect to action from the specified URL but URL in the route table has been matched.

ViewEngine in ASP.NET MVC

"View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser."
There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.

  1. Web Form View Engine was with ASP.NET MVC since beginning.
  2. Razor View Engine was introduced later in MVC3.
  3. NHaml is an open source view engine since 2007.
  4. Spark is also an open source since 2008.
Custom View Engine in MVC

Yes we have a Custom View Engine in MVC , 
by implementing the IViewEngine interface or by inheriting from the VirtualPathProviderViewEngine abstract class.

Scaffold templates in ASP.Net MVC

Scaffolding in ASP.NET MVC is used to generate the Controllers,Model and Views for
create, read, update, and delete CRUD functionality in an application. The scaffolding will be
knowing the naming conventions used for models and controllers and views.
Explain the types of Scaffoldings.

Below are the types of scaffoldings :
Empty
Create
Delete
Details
Edit
List

Significance of NonActionAttribute in MVC

In general, all public methods of a controller class are treated as action methods. 
If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.


HTML helpers in MVC

HTML helpers help you to render HTML controls in the view. For instance if you want to display a 
HTML textbox on the view , below is the HTML helper code.


1:  <%= Html.TextBox("ClientName") %>  

For checkbox below is the HTML helper code. In this way we have HTML helper methods for every
HTML control that exists.


1:  <%= Html.CheckBox("Gender") %>  

AJAX Helpers

AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which
performs the request asynchronously and these are extension methods of AJAXHelper class which
exists in namespace - System.Web.ASP.Net MVC.

Below are the options in AJAX helpers :

  1. Url : This is the request URL.
  2. Confirm : This is used to specify the message which is to be displayed in confirm box.
  3. OnBegin : Javascript method name to be given here and this will be called before the AJAX request.
  4. OnComplete : Javascript method name to be given here and this will be called at the end of AJAX request.
  5. OnSuccess - Javascript method name to be given here and this will be called when AJAX request is successful.
  6. OnFailure - Javascript method name to be given here and this will be called when AJAX request is failed.
  7. UpdateTargetId : Target element which is populated from the action returning HTML

Web API's in Asp.Net MVC

  1. Web API is a new framework for consuming & building HTTP Services.
  2. Web API supports wide range of clients including different browsers and mobile devices.
  3. It is very good platform for developing RESTful services since it talk's about HTTP.
Request flow in ASP.NET MVC framework

Request flow for ASP.NET MVC framework is as follows:

Request hits the controller coming from client. Controller plays its role and decides which model to 
use in order to serve the request. Further passing that model to view which then transforms the 
model and generate an appropriate response that is rendered to client.

Routing in MVC

Routing helps you to define a URL structure and map the URL with the controller.
For instance let's say we want that when a user types "http://localhost/View/ViewClient/", it goes to the "Client" Controller and invokes the DisplayClient action. 
This is defined by adding an entry in to the routes collection using the maproute function. 
Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.


1:  routes.MapRoute(  
2:          "View", // Route name  
3:          "View/ViewClient/{id}", // URL with parameters  
4:          new { controller = "Client", action = "DisplayClient",   
5:  id = UrlParameter.Optional }); // Parameter defaults   

Attribute Routing in MVC

ASP.NET Web API supports this type routing. This is introduced in MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like –



1:  [Route("{action = CategoryList}")] - Controller Level  
2:  [Route("Clients/{CategoryId:int:min(10)}")] - Action Level  

Just add the method – "MapMvcAttributeRoutes()" to enable attribute routing as shown below.


1:  public static void RegistearRoutes(RouteCollection routes)   
2:  {   
3:  routes.IgnoareRoute("{resource}.axd/{*pathInfo}");   
4:  //enabling attribute routing   
5:  routes.MapMvcAttributeRoutes();  
6:  //convention-based routing   
7:  routes.MapRoute  
8:  (   
9:  name: "Default",   
10:  url: "{controller}/{action}/{id}",   
11:  defaults: new { controller = "Client", action = "GetClientList", id = UrlParameter.Optional }  
12:  );  
13:  }  


ViewModel in ASP.NET MVC

A ViewModel basically acts as a single model object for multiple domain models,
facilitating to have only one optimized object for View to render.
Below diagram clearly express the idea of ViewModel in ASP.NET MVC:

There are multiple scenarios where using ViewModel becomes obvious choice. For example:

  1. Parent-Child View Scenario
  2. Reports where often aggregated data required
  3. Model object having lookup data
  4. Dashboards displaying data from multiple sources 

Repository Pattern in ASP.NET MVC

  1. -Repository pattern is used as a default entity operation that allow the decoupling of the components used for presentation. 
  2. -Repository pattern allows easy testing in the form of unit testing and mocking. 
  3. -Repository pattern will have the proper infrastructure services to be used in the web applications. 
  4. -It uses the mechanism of encapsulating that provides storage, retrieval and query for the implementation of the repository. 
  5. -Repository patterns are hard coded in the application that is to be used in ASP.NET MVC architecture
  6. -Repository pattern is useful for decoupling entity operations form presentation, which allows easy mocking and unit testing.
  7. -The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation.
  8. -Repository pattern is useful for decoupling entity operations form presentation, which allows easy mocking and unit testing.
  9. -Most common queries should also be hard coded to the Repositories as methods. Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameter less for framework to call, and the second one which takes repository as an input:
Validations in MVC

One of the easiest ways of doing validation in MVC is by using data annotations. 
Data annotations are nothing but attributes which can be applied on model properties. 
For example, in the below code snippet we have a simple Client class with a property Clientcode.
This ClientCode property is tagged with a Required data annotation attribute. In other words if this model is not provided Client code, it will not accept it.



1:  public class Client  
2:  {  
3:    [Required(ErrorMessage="Client code is required")]  
4:    public string ClientCode  
5:    {  
6:      set;  
7:      get;  
8:    }   
9:  }   

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

1:  <% using (Html.BeginForm("PostClient", "Home", FormMethod.Post))  
2:  { %>  
3:  <%=Html.TextBoxFor(m => m.ClientCode)%>  
4:  <%=Html.ValidationMessageFor(m => m.ClientCode)%>  
5:  <input type="submit" value="Submit Client data" />  
6:  <%}%>   

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.


1:  public ActionResult PostClient(Client obj)  
2:  {  
3:    if (ModelState.IsValid)  
4:    {  
5:      obj.Save();  
6:      return View("Thanks");  
7:    }  
8:    else  
9:    {  
10:      return View("Client");  
11:    }  
12:  }  


Enable data annotation validation on client side

It's a two-step process: first reference the necessary jQuery files.
The second step is to call the EnableClientValidation method.
1:  <% Html.EnableClientValidation(); %>   

Maintain sessions in MVC

Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.


  1. Temp data - Helps to maintain data when you move from one controller to another controller or from 
  2. one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
  3. View data - Helps to maintain data when you move from controller to view.
  4. View Bag - It's a dynamic wrapper around view data. When you use Viewbag type,  casting is not required. It uses the dynamic keyword internally.
  5. Session variables - By using session variables we can maintain data from any entity to any entity.
  6. Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Keep and Peek in TempData

Once "TempData" is read in the current request it's not available in the subsequent request. 
If we want "TempData" to be read and also available in the subsequent request then after reading we need to call "Keep" method as shown in the code below.


1:  @TempData["MyDat"];  
2:  TempData.Keep("MyDat");  

The more shortcut way of achieving the same is by using "Peek". This function helps to read as well advices MVC to maintain "TempData" for the subsequent request.

1:  string str = TempData.Peek("Td").ToString();  

Partial views in MVC

Partial view is a reusable view (like a user control) which can be embedded inside other view.
For example let's say all your pages of your site have a standard structure
with left menu, header, and footer controls. For every page you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.


Restrict MVC actions to be invoked only by GET or POST


We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the DisplayClient action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayClient, it will throw an error.


1:  [HttpGet]  
2:  public ViewResult DisplayClient(int id)  
3:  {  
4:    Client objClient = Clients[id];  
5:    return View("DisplayClient",objClient);  
6:  }   



Comments

Popular posts from this blog

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

Implement Nlog in .Net core MVC application part 1

Devexpress Datebox date formatting in angular 6 with example

Disable backspace key using Jquery

Angular User Session Timeout example step by step