Wednesday, March 18, 2015

ASP.NET MVC: Routing Overview

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 patterns defined in the Route table. You can register one or more URL patterns to the Route table at Application_Start event. MVC5 also supports attribute routing, to know more refer Attribute Routing in ASP.NET MVC.

How to define route...

  1. public static void RegisterRoutes(RouteCollection routes)
  2. {
  3. routes.MapRoute(
  4. "Default", // Route name
  5. "{controller}/{action}/{id}", // Route Pattern
  6. new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for above defined parameters
  7. );
  8. }
  9.  
  10. protected void Application_Start()
  11. {
  12. RegisterRoutes(RouteTable.Routes);
  13. //To:DO
  14. }
When the routing engine finds a match in the route table for the incoming request's URL, it forwards the request to the appropriate controller and action. If there is no match in the route table for the incoming request's URL, it returns a 404 HTTP status code.

Note

Always remember route name should be unique across the entire application. Route name can’t be duplicate.

How it works...

In above example we have defined the Route Pattern {controller}/{action}/{id} and also provide the default values for controller,action and id parameters. Default values means if you will not provide the values for controller or action or id defined in the pattern then these values will be serve by the routing system.
Suppose your webapplication is running on www.example.com then the url pattren for you application will be www.example.com/{controller}/{action}/{id}. Hence you need to provide the controller name followed by action name and id if it is required. If you will not provide any of the value then default values of these parameters will be provided by the routing system. Here is a list of URLs that match and don't match this route pattern.
Matching URLs
Request URL                                     Parameters
http://example.com/                      controller=Home, action=Index, id=none, Since default value of controller and action are Home and Index respectively.

http://example.com/Admin         controller=Admin, action=Index, id=none, Since default value of action is Index

http://example.com/Admin/Product   controller=Admin, action=Product, id=none

http://example.com/Admin/Product/1  controller=Admin, action=Product, id=1

http://example.com/Admin/Product/SubAdmin/1 No Match Found

http://example.com/Admin/Product/SubAdmin/Add/1 No Match Found

Examples of Valid Route Patterns in ASP.NET MVC
Route Pattern URL Example
mysite/{username}/{action} ~/mysite/jatten/login
public/blog/{controller}-{action}/{postId} ~/public/blog/posts-show/123
{country}-{lang}/{controller}/{action}/{id} ~/us-en/products/show/123
products/buy/{productId}-{productName} ~/products/but/2145-widgets

Difference between Routing and URL Rewriting

Many developers compare routing to URL rewriting that is wrong. Since both the approaches are very much different. Moreover, both the approaches can be used to make SEO friendly URLs. Below is the main difference between these two approaches.

  1. URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.
  2. Actually, URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it map to the original route.
Reference:http://www.dotnet-tricks.com/Tutorial/mvc/HXHK010113-Routing-in-Asp.Net-MVC-with-example.html

ASP.NET MVC: Action Filter Types

What are action filters?
Action Filters are custom classes that provide pre-action and post-action behavior to the controllers action methods. This is a good thing because you may be in a situation when you need some logic to be performed before or after action execution.

Provided filter types in MVC 5

Override filter
Override filter is a new filter type that is used for indicating which filters need to be overridden. When creating a custom override filter you have to implement  implement IOverrideFilter as well to declare and implement  the  FiltersToOverride property. See below:
public class CustomOverrideFilter : FilterAttribute, IOverrideFilter
{
    public Type FiltersToOverride 
    {
        get
        {
            //This property is responsible for returning the filter that needs to be overridden.
            //For example:
            return typeof (IActionFilter);
        }
    }
}
You can read more regarding the new MVC 5 filter override in this post “How to use the ASP.NET MVC 5 Filter Overrides Feature
Authentication filter
New authentication filter makes security decisions if the action should be executed or not by validating the user authentication request. Also it is responsible for updating the Principle. This is also a new filter that was released with MVC 5. While creating a custom authentication filter you have to implement IAuthenticationFilter plus declare and implement the OnAuthentication and OnAuthenticationChallenge methods. See below:
public class CustomAuthenticatioFilter : FilterAttribute, IAuthenticationFilter    
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        //This method is responsible for setting and modifying the principle for the current request though the filterContext .
        //Here you can modify the principle or applying some authentication logic.  
        //filterContext.Principal = ...;
    }
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //This method is responsible for validating the current principal and permitting the execution of the current action/request.
        //Here you should validate if the current principle is valid / permitted to invoke the current action. (However I would place this logic to an authorization filter)
        //filterContext.Result = new RedirectToRouteResult("CustomErrorPage",null);
    }
}
More regarding the new authentication filter you can find in this post “Finally the new ASP.NET MVC 5 Authentication Filters!”.
Authorization filter
Authorization filter is also responsible for making security decisions if the action should be executed or not by validating whether the user is authorized by a given criteria or validating the requests properties. While creating a custom authorization filter you have to implement the IAuthorizationFilter, declare and implement OnAuthorization. See below:
public class CustomAuthorizationFilter : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        //This method is responsible for validating the user or properties (authentication/authorization ) and checking if he as authorization 
        //access to the action / controller or system (if the custom authorization filter is registered as a global filter)
        //The user can be validate by the role or some authorization criteria that needs to be applied.
    }
}
When to use:
Lets say that you have pages or actions in your web application that can be executed only by authorized user that have a specific role. This is a good fit to use the Authorize filter attribute and specify it Roles parameter.
Another reason touse it is when you have pages or actions that can be accessed only by authorized users that get redirected or linked by a specific URL. Here you have to create a custom authorization filter: validate if the user is authorized and check that the HttpContext.Request.UrlReferrer is a valid URL.
Action filter
Action filter is responsible for performing  additional logic before and after the controllers action execution. When creating a custom action filter you have to implement the IActionFilter, declare and implement OnActionExecuting and OnActionExecuted methods. See below:
public class CustomActionFilter : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //This method gets invoked before action execution.
        //Here you can perform different operation from validating properties, adding additional properties to the context,
        //perform some additional operation even do a redirect if needed and so on.
        //In general here you will have logic that needs to be performed before action execution
    }
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //This method get invoked after action execution.
        //Here you can perform the same things as in the OnActionExecuting method,
        //the only different is that here you will be placing logic that needs to be performed before action execution.
        //Note: the filterContext.Canceled is TRUE if you change the Result to another in the OnActionExecuting method. 
        filterContext.Canceled == true;
    }
}
When to use:
Action filter is really a great thing because during the OnActionExecuting the  filterContext parameter, that passed to the method, has a lot of information about the current context. You can use this information to perform logic or you can manipulate and change the context according to your logic needs.
Action filters can be used to audit and log user activities on a set of actions or controllers or the whole application.
Result filter
Result filter is responsible for performing additional logic before and after action result execution. To create a custom result filter you’ll have to implement IResultFilter, declare and implement OnResultExecuting and OnResultExecuted. See below:
public class CustomResultFilter : FilterAttribute, IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        //This method gets invoked before the ActionResult is executed.
        //Here you can perform different operations like validate the action result that will be returned to the user,
        //replace the action result, add additional extra metadata to the HTTP context,
        //Note: You can cancel ActionResult execution by setting by setting
        filterContext.Cancel = true;
    }
    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
        //This method gets invoked after the Action is executed.
        //Here you can't update or change action result because it has already been executed.
        //However you can still write to the Http response / context.
        //Note: Indicated that the ActionResult execution was canceled (the cancelation can be done in OnResultExecuting):
        filterContext.Canceled;
    }
}
When to use:
One good example that comes into mind is changing the model that is being returned to a view model using AutoMapper or other mapping lib that you prefer. Another example is changing the result if we have an invalid model or an invalid result to redirect to an error page. And more…
Exception filter
Exception filter is responsible for handling errors that are raised by the action or action results. To create a custom exception handler you have to implement the IExceptionFilter interface, declare and implement its OnException method. See below:
public class CustomException : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        //This method gets invoked after all other filter have been executed and if an exception occurred during method execution.
        //Here you should place logic to handle the exception the way you need. 
    }
}
When to use:
Use this filter to log the exception or to redirect to another action. You may handle the exception in your application the way you need.

That’s it!

We have covered all available filter types that are provided in MVC 5 and now have a glance look how to create a custom filter of each type.

Reference:http://hackwebwith.net/asp-net-mvc-5-action-filter-types-overview/

ASP.NET MVC: Data Annotations for Model Validation

Data validation is a key aspect for developing web application. In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework orm models.
Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.

Data Annotation Validator Attributes

  1. DataType

    Specify the datatype of a property
  2. DisplayName

    specify the display name for a property.
  3. DisplayFormat

    specify the display format for a property like different format for Date proerty.
  4. Required

    Specify a property as required.
  5. ReqularExpression

    validate the value of a property by specified regular expression pattern.
  6. Range

    validate the value of a property with in a specified range of values.
  7. StringLength

    specify min and max length for a string property.
  8. MaxLength

    specify max length for a string property.
  9. Bind

    specify fields to include or exclude when adding parameter or form values to model properties.
  10. ScaffoldColumn

    specify fields for hiding from editor forms.
  11. Url   Validates that a valid URL has been supplied as a property value

Designing the model with Data Annotations

  1. using System.ComponentModel;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Web.Mvc;
  4. namespace Employee.Models
  5. {
  6. [Bind(Exclude = "EmpId")]
  7. public class Employee
  8. {
  9. [ScaffoldColumn(false)]
  10. public int EmpId { get; set; }
  11. [DisplayName("Employee Name")]
  12. [Required(ErrorMessage = "Employee Name is required")]
  13. [StringLength(100,MinimumLength=3)]
  14. public String EmpName { get; set; }
  15. [Required(ErrorMessage = "Employee Address is required")]
  16. [StringLength(300)]
  17. public string Address { get; set; }
  18. [Required(ErrorMessage = "Salary is required")]
  19. [Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
  20. public int Salary{ get; set; }
  21. [Required(ErrorMessage = "Please enter your email address")]
  22. [DataType(DataType.EmailAddress)]
  23. [Display(Name = "Email address")]
  24. [MaxLength(50)]
  25. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
  26. public string Email { get; set; }
  27. }
  28. }
Once we have define validation to the model by using data annotations, these are automatically used by Html Helpers in views. For client side validation to work, please ensure that below two <SCRIPT> tag references are in the view.
  1. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  2. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Presenting the model in the view

  1. @model Employee.Models
  2. @{
  3. ViewBag.Title = "Employee Details";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. @using (Html.BeginForm())
  7. {
  8. <div class="editor-label">
  9. @Html.LabelFor(m => m.EmpName)
  10. </div>
  11. <div class="editor-field">
  12. @Html.TextBoxFor(m => m.EmpName)
  13. @Html.ValidationMessageFor(m => m.EmpName)
  14. </div>
  15. <div class="editor-label">
  16. @Html.LabelFor(m => m.Address)
  17. </div>
  18. <div class="editor-field">
  19. @Html.TextBoxFor(m => m.Address)
  20. @Html.ValidationMessageFor(m => m.Address)
  21. </div>
  22. <div class="editor-label">
  23. @Html.LabelFor(m => m.Salary)
  24. </div>
  25. <div class="editor-field">
  26. @Html.TextBoxFor(m => m.Salary)
  27. @Html.ValidationMessageFor(m => m.Salary)
  28. </div>
  29. <div class="editor-label">
  30. @Html.LabelFor(m => m.Email)
  31. </div>
  32. <div class="editor-field">
  33. @Html.TextBoxFor(m => m.Email)
  34. @Html.ValidationMessageFor(m => m.Email)
  35. </div>
  36. <p> <input type="submit" value="Save" />
  37. </p>
  38. }
Refeerence: http://www.dotnet-tricks.com/Tutorial/mvc/D8I4270712-MVC-Data-Annotations-for-Model-Validation.html

Monday, March 16, 2015

ASP.NET MVC: Quick Reference for Beginners

  1. Installing ASP.NET MVC
  2. What asp.net mvc version is my mvc application using
  3. Creating your first asp.net mvc application
  4. Controllers in an mvc application
  5. Views in an mvc application
  6. ViewData and ViewBag in mvc
  7. Models in an mvc application
  8. Data access in MVC using entity framework
  9. Generate hyperlinks using actionlink html helper
  10. Working with multiple tables in mvc
  11. Using business objects as model in MVC
  12. Creating a view to insert data
  13. FormCollection in MVC
  14. Mapping asp.net request data to controller action simple parameter types
  15. Updatemodel function in MVC
  16. Difference between updatemodel and tryupdatemodel
  17. Editing a model in mvc
  18. Updating data in MVC
  19. Unintended updates in mvc
  20. Preventing unintended updates
  21. Including and excluding properties from model binding using bind attribute
  22. Including and excluding properties from model binding using interfaces
  23. Why deleting database records using get request is bad
  24. Deleting database records using post request in mvc
  25. Insert update delete in mvc using entity framework
  26. Customizing the auto-generated index view
  27. Customizing the autogenerated create view
  28. Customizing the autogenerated edit view
  29. Using data transfer object as the model in mvc
  30. View engines in asp.net mvc
  31. Using custom view engines with asp.net mvc
  32. How does a controller find a view
  33. Html helpers in MVC
  34. Generating a dropdownlist control in mvc using HTML helpers
  35. How to set an item selected when dropdownlist is loaded
  36. Difference between Html.TextBox and Html.TextBoxFor
  37. Generating a radiobuttonlist control in mvc using HTML helpers
  38. CheckBoxList in asp.net mvc
  39. ListBox in asp.net mvc
  40. Using displayname, displayformat, scaffoldcolumn attributes in mvc
  41. Using datatype & displaycolumn attributes
  42. Opening a page in new browser window
  43. Hiddeninput and readonly attributes in mvc
  44. Display and edit templated helpers
  45. Customize display and edit templates
  46. Accessing model metadata from custom templated helpers
  47. Displaying images in asp.net mvc
  48. Custom html helpers in mvc
  49. Html encoding in asp.net mvc
  50. Detect errors in views at compile time
  51. Advantages of using strongly typed views
  52. Partial views
  53. Difference between html.partial and html.renderpartial
  54. T4 templates in asp.net mvc
  55. What is cross site scripting attack
  56. How to prevent cross site scripting attack
  57. Razor views in mvc
  58. Razor views in mvc continued
  59. Layout view in mvc
  60. ViewStart in asp.net mvc
  61. Named sections in layout files in mvc
  62. Implementing search functionality in asp.net mvc
  63. Implement paging in asp.net mvc
  64. Implement sorting in asp.net mvc
  65. Deleting multiple rows
  66. Check uncheck all checkboxes with another single checkbox using jquery
  67. Action selectors in mvc
  68. What is the use of NonAction attribute in mvc
  69. Action filters in mvc
  70. Authorize and AllowAnonymous action filters
  71. ChildActionOnly attribute in mvc
  72. HandleError attribute
  73. OutputCache attribute
  74. CacheProfiles
  75. RequireHttps attribute
  76. ValidateInput attribute
  77. Custom action filters
  78. Different types of ActionResult in asp.net mvc
  79. Areas
  80. StringLength attribute
  81. Range attribute
  82. Creating custom validation attribute
  83. RegularExpression attribute
  84. Compare attribute
  85. Enable client side validation in asp.net mvc
  86. ValidationSummary
  87. What is Unobtrusive JavaScript
  88. Unobtrusive validation in asp.net mvc
  89. Remote validation in asp.net mvc
  90. Remote validation in mvc when javascript is disabled
  91. Create a custom remote attribute and override IsValid() method
  92. Ajax with asp.net mvc
  93. What is Ajax and why should we use it
  94. Providing visual feedback using LoadingElementId AjaxOption
  95. OnBegin, OnComplete, OnSuccess and OnFailure properties of AjaxOptions class
  96. LoadingElementDuration property of AjaxOptions class
  97. Implement autocomplete textbox functionality in mvc
  98. What is JavaScript minification
  99. What is CDN - Content Delivery Network
  100. What if CDN is down
Reference: http://csharp-video-tutorials.blogspot.co.uk/p/aspnet-mvc-tutorial-for-beginners.html

ASP.NET MVC: Partial Views

If you are an asp.net web-forms developer, then you will realize that partial views in mvc are similar to user controls in asp.net webforms. 

Partial views are used to encapsulate re-usable view logic and are a great means to simplify the complexity of views. These partial views can then be used on multiple views, where we need similar view logic.



f you are using web forms view engine, then the partial views have the extension of .ascx. If the view engine is razor and programming language is c#, then partial views have the extension of .cshtml. On the other hand if the programming language is visual basic, then the extension is .vbhtml.
Partial views in mvc

Let us understand partial views with an example. We want to display, employee photo and his details as shown in the image below.
partial view example

Index Action() method in HomeController retrurns the list of employees.
public ActionResult Index()
{
    SampleDBContext db = new SampleDBContext();
    return View(db.Employees.ToList());
}

We will have the following code in Index.cshtml. This view is a bit messy and complex to understand.
@model IEnumerable<MVCDemo.Models.Employee>
@foreach (var item in Model)
{
    <table style="font-family:Arial; border:1px solid black; width: 300px">
        <tr>
            <td>
                <img src="@Url.Content(item.Photo)" alt="@item.AlternateText" />
            </td>
            <td>
                <table>
                    <tr>
                        <td><b>Age:</b></td>
                        <td>@item.Age</td>
                    </tr>
                    <tr>
                        <td><b>Gender:</b></td>
                        <td>@item.Gender</td>
                    </tr>
                    <tr>
                        <td><b>Salary:</b></td>
                        <td>@item.Salary</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
}

To simplify this view, let's encapsulate the HTML and code that produces the employee table in a partial view.

Right click on the "Shared" folder and add a view. Set
View name = _Employee
View engine = Razor
Create a strongly typed view = Checked
Model class = Employee (MVCDemo.Models)
Scaffold template = Empty
Create as a partial view = Checked

This should add "_Employee.cshtml" partial view to the "Shared" folder.

Please note that, partial views can be added to "Shared" folder or to a specific views folder. Partial views that are in the "Shared" folder are available for all the views in the entire project, where as partial views in a specific folder are available only for the views with-in that folder.

Copy and paste the following code in "_Employee.cshtml" partial view
@model MVCDemo.Models.Employee
<table style="font-family:Arial; border:1px solid black; width: 300px">
        <tr>
            <td>
                <img src="@Url.Content(Model.Photo)" alt="@Model.AlternateText" />
            </td>
            <td>
                <table>
                    <tr>
                        <td><b>Age:</b></td>
                        <td>@Model.Age</td>
                    </tr>
                    <tr>
                        <td><b>Gender:</b></td>
                        <td>@Model.Gender</td>
                    </tr>
                    <tr>
                        <td><b>Salary:</b></td>
                        <td>@Model.Salary</td>
                    </tr>
                </table>
            </td>
        </tr>
</table>

Now, make the following changes to Index.cshtml view. Notice that the view is much simplified now. To render the partial view, we are using Partial() html helper method. There are several overloaded versions of this method. We are using a version that expects2 parameters, i.e the name of the partial view and the model object.
@model IEnumerable<MVCDemo.Models.Employee>
@foreach (var item in Model)
{
    @Html.Partial("_Employee", item)
}

ASP.NET MVC: Developing Extension in MVC (HTML Helper For Image (@Html.Image): )

Today I worked on a project where I am required to display an image on the web page. As you know there is not a HTML Helper for images yet. Look at the following screen, we can't see an image here:

Developing-Extension-in-MVC.png
Before proceeeding in this article, let me share the sample data source here (I can't share the original data so I created a set of dummy data with a controller here):

Data Source & Controller

Extension-in-MVC.gif

View
Html-Helper-for-Image2.png

As in the above image, the first one (@Html.DisplayFor…) is generated by scaffolding for me (marked as a comment in the above view) and the second one is an alternative that will work.

So, we don't have a HTML helper to deal with images using Razor syntax! Wait wait. We can develop an extension method for this that will allow us to work with images. Let's get started.

Step 1: Add a class file using the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication8.Models
{
    public static class ImageHelper
    {
        public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height)
        {
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", src);
            builder.MergeAttribute("alt", altText);
            builder.MergeAttribute("height", height);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }

}
The above "Image" function has the "MvcHtmlString" type and will accept a four-parameter helper (helper type "image"), src (image path), altText (alternative text) and height (height of image) and will return a "MvcHtmlString" type.

Step 2: In the view, comment-out the last line (HTML style approach) and use the new extended method for the image, as in:

Html-Helper-for-Image3.gif

Note: Please note to use "@using MvcApplication8.Models" namespace on each view page to enable this new HtmlHelper.

Step 3: If you put a breakpoint on the extension method then you will notice that the method returns the exact markup that we need.

Extension-method-in-MVC.gif

Hope this helps.

Reference: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/html-helper-for-image-html-image-developing-extension-in/