MVC Tutorials

 

                                            MVC

Topics:

  1. MVC
  2. Routing
  3. Layout
  4. Partial View
  5. Bundling And Minification
  6. Data Transportation In MVC
  7. Helper Class
  8. Action Method
  9. Data Annotation
  10. Filters

  

 

1.MVC:- MVC is a software architecture pattern. Using MVC pattern we can generate multiple view of same data. It separates the application into three parts Model,View and Controller. 

Model:- Model represents data of the application. Model objects retrieve and store model state in a database.

View:- View is a user interface. View display data using model to the user and also enables them to modify the data.

Controller:- Controller handles the user request. The controller renders the appropriate view with the model data as a response.

 

Note:- We can't use Controller Name same as Application Name. This show error this(Ex-Employee) is a namespace but used as a type.

Namespace:System.Web.Mvc;

 

2.Routing:- Routing is a pattern matching system that is responsible for mapping incoming https request to the specific Controller action method.

 

Basically routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. At runtime ,routing engine use the route table for matching the incoming request 's url pattern against the url pattern defined in the route table.

 

Routing is a mechanism that eliminates the need of matching each url with a physical file. It enables us to define a Url pattern that maps to a request handler. In MVC,Request handler is  a Controller class or Action method.

 

How Routing Works:-

When the MVC application launches the Application_Start() event handler of the global.asax execute that call the RegisterRoutes() method from RouteConfig class under App_Start directory (App_Start/RouteConfig.cs). The RegisterRoutes() route has a parameter that is a collection of routes called the RouteCollection that contains all the registered routes in the application. 

-Route And RouteTable:Route defines the URL pattern and handler information. All the configured routes of an application stored in RouteTable and will be used by Routing engine to determine appropriate handler class or file for an incoming request.

 

And there are two types of routing possible in MVC

1.Convention based routing:- In Convention based routing we define route in RouteConfig.cs class file.

2.Attribute routing:- Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required

Attribute Routing (introduced in MVC 5) is the ability to add routes to the Route Table via attributes so that the route definitions are in close proximity to their corresponding actions.

To enable Attribute Routing, we need to call the MapMvcAttributeRoutes method of the route collection class during configuration

 

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapMvcAttributeRoutes(); //Enables Attribute Routing

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

            );

        }

    }    

 

Note:- We can not use one route for multiple action method but we can use multiple route for one action method.

Ex-

  [Route("~/aboutus")]   

  [Route("~/about-us")]  

  public string AboutUs()

  {

    return "this is about us";

  }

 

  •  Here Tild(~) sign used for override prefixed route name.
  •  [RoutePrefix("students")] // set a common prefix for the entire controller(all action method within the controller).
  •  Route constraint is way to put some validation around the defined route.

 

NameSpace:System.web.Routing.

  

3.Layout:- Layout View is like a master page in asp.net and provide a default look and feel to all the child view.

Layout used two methos RenderBody and RenderSection for renders child view.

1)RenderBody():- RenderBody() renders all the content of the child view which is not part of the named section.The RenderBody() method must be present in the layout view.A Layout page can have only one RenderBody method but can have multiple RenderSection method beacause a layout page can render only one child view at a time but we can defined many section on the layout page corresponding to child view.    

The views which will be displayed in a placeholder RenderBody() are called child views. There are multiple ways to specify which layout view will be used with which child views. You can specify it in a common _ViewStart.cshtml, in a child view, or in an action method.

The default _ViewStart.cshtml is included in the Views folder.  Viewstart.chtml file makes the layout common across the all views.

The _ViewStart.cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder.

2)RenderSection():-  RenderSection() renders only a part of the child view which is wrapped under the named section.Or We can say that RenderSection() method used to render sections of the child view on the layout view.  

RenderSection expects one parameter and that is the name of the section.

@RenderSection("scripts", required: false)

Here we render scripts section of child view using RenderSection method.By default, Sections are required, meaning each child view must define the section. We pass required: false to designate that the section is optional. 

Note:- RenderSection method used for defined multiple section on layout page corresponding to child view so that we could define different style menu for every child view(if we need that). Render section also makes possible to load only one child view javascript at a time to minimize the page load(We can define every child view javascript file in named section of every child view).   

How to create sections or named section on the child view:-

Syntax:-

@section section_name{}

Example:-

@section Scripts{ 

    @Scripts.Render("~/bundles/jqueryval"

}

So here we created a name section "Scripts" on Child View.  

 

RenderPage():- Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like Html.RenderPartial(). You can supply any model you like to the view by including it as a second parameter.

Layout pages can also contain content that can be filled by other pages on disk. This is achieved by using the RenderPage method. This method takes either one or two parameters. The first is the physical location of the file, the second is an optional array of objects that can be passed into the page.

RenderPage(string path, params object[] data);.

    @RenderBody("~/Views/Shared//MyView.chtml",MyModel)

Note:- 

1.RenderPage is used to render a view in another view.                                     2.We can used RenderPage() for render partial view

Note:- A Layout page can have only one RenderBody(),but multiple sections and multiple RenderPage().

 

4.Partial View:- Partial View is reusable and customizable component that is used as child view in another View. MVC provide four Helper method for rendering a Partial View.

                              OR

A common view code(html code) which is available for all the Views in website is known as partial view. Always put common code in shared folder.

1)Html.Partial:- Return a string(MvcHtmlString) and we can store the output in a variable for amendment.

<div>

    @Html.Partial("_address")

</div> 

2)Html.RenderPartial:-  Returns void and writes result(html) directly to the http response stream.It perform better than html.partial.

<div>

    @{Html.RenderPartial("_address");}

</div>

 

 3) @Html.Action()            4) @Html.RenderAction()

Note:- Action and RenderAction are same as Partial and RenderPartial but when we want to render partial view using child action method then we use it.

 

# Diff between @RenderPage() and @{Html.RenderPartial();}.

 We generally use Html.Partial for render Partial View but we can also use @RenderPage() for render Partial View.In RenderPage we need to defined path and file name of the specified view while in RenderPartial we just need view name.    

 

 # Diff between View,Layout and PartialView.

 Every view is partial view without layout page.

 

 

5.Bundling and Minification:-

Namespace:System.web.Optimization

Bundling: Bundling is a technique to improve performance by reducing the number of request to the server. Bundling allow us to load the bunch of static files from the server into one http request. Instead of fetching all resources(css and js files) one by one we creates a bundle(group of resources) and fetch that bundle in one single request.

Minification:- MVC implements a process called minification on the bundled files. Minification removes all whitespace and renames variables to their shortest possible name, thereby removing all excess characters (and thereby excess file size) from the bundle. Because the file is smaller, it takes less time to download.

Bundle Types

MVC 5 includes following bundle classes in stem.web.Optimization namespace:

ScriptBundle:- ScriptBundle is responsible for JavaScript minification of single or multiple script files.

StyleBundle:- StyleBundle is responsible for CSS minification of single or multiple style sheet files.

DynamicFolderBundle:- Represents a Bundle object that ASP.NET creates from a folder that contains files of the same type

Scripts.Render():- This method is used for bundling, if you bundle multiple scripts together and give them a name, then you can render them all together using this statement.

Style.Render():- This method calling the files included in that particular bundle which is declared inside the BundleConfig class in the App_Start folder.In that particular case The call to @Styles.Render("~/Content/css") is calling "~/Content/site.css".

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

Bundling and minification can be enabled or disabled in two ways:-

1.<system.web>

    <compilation debug="true" />

</system.web>

2.BundleTable.EnableOptimizations = true;

@Script.Render();

Namespace:- using System.Web.Optimization;

 

 

6.DataTransportation Technique In MVC:-

(A)Send Data Controller To View:-

1. View Data

2. View Bag

3. Session

3. Temp Data

4. Dynamic Model

6. Strong Binding

7. JavaScript(JQuery Ajax Method)

  

1)ViewData

1.ViewData used to send data from controller to view.

2.ViewData is derived from ViewDataDictionary which is a dictionary type.

3.ViewData life only for current http request.If redirection occurs ViewBag value will be null.

4.ViewData value must be typecast before use. 

5.ViewData is a dictionary which can contain key-value pairs where each key must be string.

 

2)ViewBag

1.ViewBag used to send data from controller to view.

2.ViewBag life only for current http request.If redirection occurs ViewBag value will be null. 

3.You can assign any number of propertes and values to ViewBag.

4.ViewBag is actually a wrapper around ViewData.

5.ViewBag is the dynamic property of ControllerBase class which the base class of all the Controller.

 

3)TempData:Keep and Peek method

1.TempData Used to pass, store data between subsequent request.

2.Retained the value between redirection.

3.TempData is derived from TempDataDictionary which is a dictionary type.

4.TempData internally use Session to store the data if we close the session in application then temp data will not work.

5.TempData value must be type cast before use. Check for null values to avoid runtime error.

6.TempData can be used to store only one time messages like error messages, validation messages.

7.Call TempData.Keep() to keep all the values of TempData in a third request.

 

Keep:- Save the data for next http request.

Peek:- Read the data from previous http request and Save the data for next http request.

 

 

 (B)Send Data View To Controller or (Bind View Data To Controller)

  1. Using Parameters
  2. Using Request
  3. Using Form Collection
  4. Using Strong Binding(Model Binder)
  5. Using JavaScript(JQuery Ajax Method)

   

(C). Pass multiple model on single View:-

1. ViewModel

2. DynamicModel(expando Object)

3. ViewBag

4. ViewData

5. PartialView

6. Tuples

 

 7.HelperClass In MVC:-

 

1. HtmlHelperClass

2. UrlHelperClass

3. AjaxHelperClass

 

HtmlHelperClass:- Using the HTML Helper class, we can create HTML Controls programmatically. HTML Helpers are used in View to render HTML content. HTML Helpers (mostly) is a method that returns a string. HTML Helpers are more lightweight as compared to ASP.NET Web Form controls as they do not use ViewState and do not have event models.

HTML Helpers are categorized into three types:

A)Inline HTML Helpers:-Used only on that view where they are created.

B)Built-in HTML Helpers

C)Custom HTML Helpers

 

B)Built-in HTML 

Built-in HTML Helpers are further divided into three categories:

 

1)Standard HTML Helpers:- Standard html helper also called loosely type html helper.

·  @Html.BeginForm()              
·  @Html.EndForm()             
·  @Html.ActionLink()                     
·  @Html.RouteLink()              
·  @Html.Label()              
·  @Html.TextBox()              
·  @Html.DropDownList()              
·  @Html.CheckBox()              
·  @Html.RadioButton()              
·  @Html.Hidden()              
·  @Html.Password()            
·  @Html.ValidationSummary          
·  @Html.Partial()          
·  @Html.RenderPartial()              
·  @Html.Action() 
·  @Html.RenderAction()  
            

             

 

 

2)Strongly Typed HTML Helpers:- Strongly Typed Helper requires lambda expressions.To use Strongly Typed Helper method, we first have to make Strongly Typed View.

 

·  @Html.TextBoxFor()
·  @Html.TextAreaFor()         
·  @Html.DropDownListFor()                   
·  @Html.CheckboxFor()                  
·  @Html.RadioButtonFor()                  
·  @Html.ListBoxFor()                   
·  @Html.PasswordFor()                   
·  @Html.HiddenFor()                   
·  @Html.LabelFor()                   
·  @Html.ValidationMessageFor                   

 

3)Templated HTML Helpers:-

These methods are very flexible and generate the HTML element based on the properties of the model class. We have already seen an EditorFor Helper method in the previous example, which generates TextArea element because we have declared MultiLine Datatype on Address property. Display, DisplayFor, Editor, and EditorFor are the examples of Template Helper method.

·  @Html.DisplayNameFor()       
·  @Html.DisplayFor()        
·  @Html.EditorFor()        

 

 

Note :-

· @ symbol used to access reserved keyoword on view.

· third parameter in html helper used for html modification.

 

 

C)Custom Html Helper:-

 FirstMethod:-  Using Static Method

·  Static Class       

·  Static Method        

·  IHtmlString       

·  MvcHtmlString       

 

 public static class CustomHelper

    {

        public static IHtmlString Image(string src,string alt)

        {

            return new MvcHtmlString(string.Format("<img src='{0}',alt='{1}'></img>",src,alt));

        }

    }

 

SecondMethod:- Using Extension Methods

 

 public static class CustomHelper

    {   

        public static IHtmlString Img(this HtmlHelper helper, string src, string alt)

        {

            return new MvcHtmlString(string.Format("<img src='{0}',alt='{1}'></img>", src, alt));

        }      

    }

 

Third Method:- Using TagBuilder

 

 public static class CustomHelper

    {       

        public static IHtmlString TagImg(this HtmlHelper helper, string src, string alt)

        {

            TagBuilder tag = new TagBuilder("img");

            tag.Attributes.Add("src", src);

            tag.Attributes.Add("alt",alt);

            return new MvcHtmlString(tag.ToString());

        }

    }

 

       

UrlHelperClass:- Contains methods to build URLs for ASP.NET MVC within an application.

@Url.Action()

@Url.Content()

@Url.Encode()

@Url.HttpRouteUrl()

@Url.IsLocalUrl()

@Url.HttpRouteUrl()

 

AjaxHelper:- In today's modern era, people want rich web applications. For developing this kind of application, we need to use AJAX in one or another way. Using ajax helpers in asp.net mvc, we can send data to a server in an asynchronous way without postbacks that will make our applications interactive, easy to use, and make end-users happy.

When Html helpers used Ajax internally then these new helpers are called Ajax helpers.

·         @Ajax is used to access ajax helpers

·         Ajax helpers are used on view.

 

@Ajax.ActionLink() 

@Ajax.ActionLink("Get User Details""GetDetails"new AjaxOptions

 {UpdateTargetId="divGetAllUsers",HttpMethod="GET",OnSuccess="fnSuccess",})

 

@Ajax.BeginForm()

@using (Ajax.BeginForm("Action Name""Controller Name"new AjaxOptions()

{ OnSuccess = "fnSuccess", OnFailure = "onFailure" }))

 

Why Should we Use:-

·  Ajax helpers works async on view.

·  If we are use ajax helpers we don't need to write jquery ajax function.

· These are used to get/post data from controller without refreshing entire page.

·  When you need to update a particular part of page without refreshing entire page then these are best.

 

Using AJAX, we can update the partial part of the view without posting the entire page to the server. Here we will see how to use AJAX helper in asp.net mvc to submit forms and use the AJAX action link to invoke the action method asynchronously by using JavaScript. Before starting with the demo on AJAX helper, let's look at various properties of AjaxOptions.

· Confirm:- Gets or sets the message to display in a confirmation window before a request is submitted. 

 

· HttpMethod:- Gets or sets the HTTP request method ("Get" or "Post").       

 

· InsertionMode:- Gets or sets the mode that specifies how to insert the response into the target DOM element.

There are three Insertion mode avaliable

·         Replace                       Replace the element.

·         InsertBefore                Insert before the element.

·         InsertAfter                   Insert after the element.

·         ReplaceWith

 

· LoadingElementDuration:Gets or sets a value, in milliseconds, that controls the duration of the animation when showing or hiding the loading element.        

 

· LoadingElementId:Gets or sets the id attribute of an HTML element that is displayed while the Ajax function is loading.       

 

· OnBegin:Gets or sets the name of the JavaScript function to call immediately before the page is updated.       

 

·  OnComplete:Gets or sets the JavaScript function to call when response data has been instantiated but before the page is updated.

 

· OnFailure:Gets or sets the JavaScript function to call if the page update fails.

 

· OnSuccess:Gets or sets the JavaScript function to call after the page is successfully updated.

 

· UpdateTargetId:Gets or sets the ID of the DOM element to update by using the response from the server.

 

· Url:Gets or sets the URL to make the request to.

 

When To Use:- Here big question will raise, both HTML helper and AJAX helper method generate the anchor tag then why we need to use the @AJAX.ActionLink instead of @HTML.ActionLink

· When the user clicks on the link and it want to redirect to another page then we can use @HTML.ActionLink.

· When the user clicks on the link and don’t want to redirect to different page, need to stay on the same page (without Post Back), then we can go for @AJAX.ActionLink.

 

Difference between Html and Ajax helper:-

· HTML helper class performs request synchronously.

· Ajax helper class performs request asynchronously.

· Both have same Namespace: System.Web.Mvc.

 

 

Required Refrence:- To get AJAX helper support in your project, you must have jquery.min.js and jquery.unobstrusive.ajax.js script library in your project.You can get this library via NuGet package manager console or NuGet package dialog.

<package id="jQuery" version="1.10.2" targetFramework="net452" />

<script src="~/Scripts/jquery-1.10.2.min.js"></script> 

<package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.6"/>

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

 

Required Configuration:-

  <appSettings>

    <add key="ClientValidationEnabled" value="true"/>

    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

  </appSettings>

 

8.Action Method:- All the public method of a controller are called action method.Action method handle the user request on the basic of http attribute like HttpPost,HttpGet,Put,Delete.

ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.

They are like any other normal methods with the following restrictions:

·  Action method must be public. It cannot be private or protected       

·  Action method cannot be overloaded       

·   Action method cannot be a static method.      

 

 

Action Selectors:- Action Selector is the Attribute that applied to the action method.It helps routing engine to select the current action method to handle a particular request.MVC 5 includes the following action selector attributes:

·  ActionName:-Provide a different name other than action name.       

· NonAction:-Indicate that public method of a controller is not action method.Non Action method can not responde to user request.        

·  ActionVerbs:-The ActionVerbs selector is to handle different type of Http requests.        

Note:- The MVC framework includes HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions, and HttpPatch action verbs. You can apply one or more action verbs to an action method to handle different HTTP requests. If you don't apply any action verbs to an action method, then it will handle HttpGet request by default.we can also apply multiple action verbs using the AcceptVerbs attribute, as shown below.

 [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]

          public ActionResult GetAndPostAction()

          {

            return RedirectToAction("Index");

          }

 

ActionResult:- ActionResult is abstract class and the result type of an action method. ActionResult abstract class provide many subtype

Like:-

A)Content Returing Result type and their return type

1.ViewResult

·View

2.JsonResult

·JSON

3.PartialViewResult

·PartialView

4.FileContentResult

·File

5.FilePathResult

·File

6.FileStreamResult

·File

7.EmptyResut

·Nothing

8.ContentResult

·Content

9.JavaScriptResult

·JavaScript

 

B)Redirection Result type and their return type

10.RedirectResult  --redirects to the specified URL.

· Redirect

· RedirectParmanent

·          return Redirect("http://www.google.com");

11.RedirectToRouteResult

· RedirectToRoute

· RedirectToRoutePermanent

· RedirectToAction

· RedirectToActionPermanent

 

C)Status Result type and their result type

12.HttpStatusCodeResult

13.HttpNotFoundResult->HttpNotFound

14.HttpUnathorizedResult

   

9.Data Annotation:- Data annotation are attribute that configure model class and provide validations at server side or client side.

Note: By default the validation done using Data Annotation attributes is Server Side. And hence to make it work Client Side, the Client Side validation must be enabled.

Types Of Validation

·  ClientSide Validation

·  ServerSide Validation

·  Custom Validation or Remote Validation

   

1.ClientSide Validation:- There are 2 simple steps to enable client side validation in asp.net mvc

Step 1: Enable ClientValidation and UnobtrusiveJavaScript in web.config file.

<appSettings>

    <add key="ClientValidationEnabled" value="true" />

    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

</appSettings>

 

Step 2: Include a reference to the following javascript files. In realtime, the references to the javascript files are included in the master page. This avoids the need to reference them on each and every view where we need validation. The order in which the script files are referenced is also important. jquery.validate is dependant on jquery and /jquery.validate.unobtrusive is dependant on jquery.validate, so they should be referenced in the following order. Otherwise, client side validation will not work. In short, JavaScript is parsed "top-down", so all dependencies need to be referenced before the dependant reference.

<script src="~/Scripts/jquery-3.5.1.min.js"></script>

<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

or

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")

}

With these 2 changes, validation should now happen on the client without a round trip to the server. If the client disables javascript in the browser, then client side validation does not work, but server side validation will continue to work as normal.

2.Server Side Validation:- Tools to Enable Server Side Validation in Asp.net Mvc

· ModelState.IsValid

· ValidationMessageFor()

· ValidationSummary()

· ModelState.AddModelError()

 

First-Step:-Add Data Annotation to Model

 

          [Required(ErrorMessage ="Please Enter Student Name")]       

           public string Name { getset; }

 

Second-Step:- Check Validation at Controller Level

            if (ModelState.IsValid)

            {

                _context.Students.Add(student);

            }

            else

            {

                return View();

            }

 

Third-Step:- Add Validation Message at View

@Html.ValidationMessageFor(model => model.Name) 

 

Note:- Need some changes to site.css for style the error message

.field-validation-error {

    color:red;

}

 

.input-validation-error {

    border:2px solid red;

}

your can see these class using inspect the input field in browser.

 

Note:- if we are not taking layout page in child view then need to add

@section Scripts {

    @Scripts.Render("~/bundles/jquery")

} 

 

in child view otherwise it is already in layout page.

3.Custom or RemoteAttriue Validaton:-We can create custom or remote validation for both, client side and server side validation.For makig custom attribute we implement ValidationAttribute abstract class.

Some Data Annotaion   

        [Required]

        [MinLength]

        [MaxLength]         

        [StringLength]  

        [Range]    

        [DataType]       

        [RegularExpression]

        [EmailAddress]

        [Compare]

        [Phone]       

        [DisplayFormat]

        [ConcurrencyCheck] 

        [Table]

        [Key]

        [ForeignKey]

        [DatabaseGenerated]

        [Column)]

        [Display]

        [DisplayName]

        [DisplayColumn]

        [Timestamp]     

        [Index]

        [NotMapped]      

        [ScaffoldColumn]

        [ComplexType]

        [InverseProperty]       

        [MetadataType]

        [AllowHtml]

 

Note:- Display (name="") Vs DisplayName ("") attributes.

Display allows you to use resource files to support globalization and different languages. I tend to use DisplayName most of the time, but if you need to include a resource file with multiple languages based on locale, then you might want to use Display.

using System.ComponentModel.DataAnnotations;  //needed for Display annotation

using System.ComponentModel;  //needed for DisplayName annotation

 

10.Filters:- Filters are attribute which are used to perform some logic before and after a action method is called.

Note:- All Filters works on Action,Controller and Global Level. 

# Need Of Filters:- Basically, ASP.NET MVC Filters are used to perform the following common functionalities in your application.

· Caching        

· Error Handling        

· Logging        

· Permission(Authentication and Authorization)        

· etc.        .

 

# Types of filters:- In MVC5, There are five type of filters and all these filters are also called action filter and as per requirement we can create custom filters for all type of filters.

1. Authentication filter     

2. Authorization filter     

3. Action filter     

4. Result filter     

5. Exception filter     

 

Note:- This is also order of execution of all filter. 

1)Authentication:- This filter checks that the user from where the request is coming is a valid user or not. The Authentication filters in MVC implements the IAuthenticationFilter interface.

Types of Authentication Mode:-

 

  <system.web>

      <authentication mode="Forms">

      <forms loginUrl="Account/Login"></forms>

      </authentication>

  </system.web>

 

·         Forms

·         Windows

·         Passport

·         Federated

·         None 

2)Authorization:- The Authorization Filters executed after the Authentication Filter. This filter is used to check whether the user has the rights to access the particular resource or page. The built-in Authorize and RequireHttps Attribute are examples of Authorization Filters.

3)Action:- The Action Filter will be executed before the action method starts executing or after the action has executed. So, if you want to execute some custom logic that should be get executed before and after an action method executes, then you need to use the Action Filters in MVC applications         

4)Result:- Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser. 

5)Exception:- We can use the Exception Filter in MVC Application to handle any exceptions that occur during MVC Request processing pipeline.

 # Predefined Filters:- Some of the filters are already built by the ASP.NET MVC framework and they are ready to be used. For example

 

·         Authorize filter

·         ValidateInput filter

·         RequireHttps filter

·         HandleError filter

·         OutputCache filter

·         etc

 

1)Authorize filter [Authorize]:- It's a type of Authorization filter.This action filter enables you to restrict access to a particular user or role. 

2)ValidateInput filter [ValidateInput(false)]:- It is a type of Authorize filter. This filter used to prevent XSS attacks on [AllowHtml] text fields. 

3)RequireHttps [RequireHttps]:- It is a type of Authorize filter.The RequireHttps Attribute in ASP.NET MVC forces an unsecured HTTP request to be re-sent over HTTPS. 

4)HandleError filter [HandleError]:- Error handling is the main concern in any application.As per the C# guidelines we use try catch block to handle exceptions.Usually we put code in try block and catch the exception in catch block.But this is not the recommended way in MVC.

Asp.Net MVC framework provides a built in filter to handle exception andd this filter is called known as HandleError

·  HandleError is a type of Exception Filter.

·  Using HandleError we can avoid try catch.

·  HandleError works on Action,Controller,Global level.

 

   To Use HandleError in MVC Application,following 3 things are required

 

· Enable Custom error in web.config.

<system.web>

    <customErrors mode="On"></customErrors>

</system.web>

 

· Add error.cshtml view in shared folder.

· Use HandleError attribute at Action/Controller/Global level.    

 

This filter has some limitation

· we can not log error usig hadle error attriute.

· This does not support to 401(Unauthorized) ,404(Resource not found) error.

HTTP Error 401.0 - Unauthorized

You do not have permission to view this directory or page.

404:-Page/View not found

 

5)OutputCache filter [OutputCache]:- Its a type of Action filter.This filter is used to cache data of a particular action method for a specific time.we use OutputCache attribute to implement Output Cache filter.To set the time we use duration property which stores data in second.

 

Custom Filters:- Every filter can be custom filter.For creating custom filter create a class and implement ActionFilterAttribute or FilterAttribute Class and Corresponding interface which filter we want to create like for Action Filter use IActionFilter Interface.

 

      public class MyActionFilter : FilterAttributeIActionFilter

            {

        public void OnActionExecuted(ActionExecutedContext filterContext)

        {  

            Debug.WriteLine("hello from action filter onactionexecuted");

            filterContext.Controller.ViewBag.Message = "Nitish from action filters";

            //throw new NotImplementedException();

        }

       

        public void OnActionExecuting(ActionExecutingContext filterContext)

        {   //first execute

            Debug.WriteLine("hello from action filter onactionexecuting");

            //throw new NotImplementedException();

        }

             }

 

Note:- OnActionExecuting method excuted before OnActionExecuted and both method executed before result is render.

 

ActionFilterAttribute:- 

FilterAttribute:-  Filter attribute represents the base class for action and result filter attributes. 

Attributes:- Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection.

 

 

Model Binder:- Model Binder used for model binding. Model Binder maps http request to action  parameter. Parameter can be any type integer, string, decimal, complex type 

 

ModelState:- ModelState is a property of controller that is used for validating form in server side. You must add System. Web. Mvc namespace in order to use it.


Encoding Type:- Encoding type in form data

@using (@Html.BeginForm("Create","Employee",FormMethod.Post, new { enctype="multipart/form-data" }))

·         application/x-www-form-urlencoded (the default)

·         multipart/form-data

text/plain

 

View Model:- ViewModel is a plain class with properties, which is used to bind it to strongly typed view. ViewModel can have the validation rules defined for its properties using data annotations.

View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements. Few examples of View Models are below

To list data from more than one entities in a view page – we can create a View model and have properties of all the entities for which we want to list data. Join those database entities and set View model properties and return to the View to show properties of different entities in one table as one result set.

View model may define only specific fields of a single entity that is required for the View.

 

Strongly Typed View:- In ASP.NET MVC, we can pass the data from the controller action method to a view in many different ways like ViewBag, ViewData, TempData and strongly typed model object. If we pass the data to a View using ViewBag, TempData or ViewData, then that view becomes a loosely typed view.

Strongly typed views are used for rendering specific types of model objects, instead of using the general ViewData structure. By specifying the type of data, you get access to IntelliSense for the model class.

The view which binds to a specific type of model is called as Strongly Typed View. By specifying the model, the Visual studio provides the intellisense and compile time checking of type.


View Engine And Razor:- View Engine in Asp.Net MVC is used to translate our view to HTML and then render to browser. Razor allows us to write clean and combine HTML and C# code.Ex:-NHaml,WebMatrix,Spark.


Area:- Areas are some of the most important components of ASP.NET MVC projects. The main use of Areas are to physically partition web project in separate units.  In short, an area can be defined as: Smaller functional units in an ASP.NET MVC project with its own set of controllers, views, and models. 


Scaffolding:- It is nothing but automatic code generation framework of ASP.NET web application. It generates code for CRUD operations using the Entity Framework models.

Edit

List

Delete

Empty

Create

Details

Note:-

1.There is no need to add dbcontext class for generate a view with scaffolding(create,edit,list etc) but when you don't have a dbcontext class in your model it will not show in scaffolding wizard but it will show when you have dbcontext class in your folder.

2.Also can include datatype like [DataType(DataType.Date)] without datacontext class it will reflect on viw as calender.

3.But always need dbcontext class when we do scaffolding from Controller.     

4.Controller Scaffolding will not create dropdownlist for Department if we will not use( ICollection<> )

public ICollection<Employee> Employee { getset; } in Department Class

 

@Model vs @model:-  

ActionResult Vs JsonResult:- The GET request by default not allowed in JSON result so to allow GET request in JsonResult we need to set JsonRequestBehavior to AllowGet.

Example:- using Newtonsoft.Json;:-Use to convert object into json.

 

        [HttpGet]

        public JsonResult GetStudent()

        {

            Student std = new Student()

            {

                Id=1,

                Name="Mittal"

            };

            var json = JsonConvert.SerializeObject(std);

            return Json(json, JsonRequestBehavior.AllowGet);

        }


RedirectToRoute vs RedirectToAction:- Both are return type of RedirectToRouteResult.Redirect to route looks up the route table thats defined in global.asax and redirect to action redirects you to a specified controller/action.

return RedirectToAction("MyIndex");

 

Redirect vs RedirectParmanent:- Both are return type of RidrectResult.The basic difference between the two is that Redirect will send an HTTP 302(Moved Temporary) status code whereas RedirectPermanent sends the browser an HTTP 301 (Moved Permanent) status code .

RedirectResult  --redirects to the specified URL. 

RedirectResult Redirect(string url);

RedirectResult RedirectPermanent(string url); 

 public RedirectResult Index()

 {

 return Redirect("http://www.google.com");

 return RedirectPermanent("http://www.google.com")

 }

  

Unobtrusive AJAX:- ASP.NET MVC supports unobtrusive Ajax which is based on jQuery. The unobtrusive Ajax means that you use helper methods to define your Ajax features, rather than adding blocks of code throughout your views.

Ajax allow web pages to exchange data asynchronously with the server in order to update specific portions of the page rather reloading its entire content. This will enhance the responsiveness and performance of the web applications.


=>Difference between @Html.Action() ,@Html.ActionLink(),@Html.RenderAction() and @Url.Action() and @Html.RouteLink().

No comments:

Post a Comment