Friday, 18 July 2014

Routing MVC 4

Routing
·         All ASP.NET MVC traffic starts out like any other website traffic: with a request to a URL. This means that, despite the fact that it is not mentioned anywhere in the name, the ASP.NET Routing framework is at the core of every ASP.NET MVC request.
·         In simple terms, ASP.NET routing is just a pattern-matching system. At startup, the application registers one or more patterns with the framework’s route table to tell the routing system what to do with any requests that match those patterns.
·         When the routing engine receives a request at runtime, it matches that request’s URL against the URL patterns registered with it (Figure 1-6).
·         When the routing engine finds a matching pattern in its route table, it forwards the request to the appropriate handler for that request.
Otherwise, when the request’s URL does not match any of the registered route patterns, the routing engine indicates that it could not figure out how to handle the request by returning a 404 HTTP status code.
Configuring Routes
ASP.NET MVC routes are responsible for determining which controller method (otherwise known as a controller action) to execute for a given URL. They consist of the following properties:
Unique name : A name may be used as a specific reference to a given route
URL pattern : A simple pattern syntax that parses matching URLs into meaningful 
segments

   
                                                         Figure 1-6. ASP.NET routing
Defaults : An optional set of default values for the segments defined in the URL pattern Constraints
A set of constraints to apply against the URL pattern to more narrowly define the URLs that it matches
The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the URL for a given request into three named segments, wrapped with brackets ({}):
 “controller”, “action”, and “id”: {controller}/{action}/{id} This route pattern is registered via a call to the MapRoute() extension method that runs during application startup (located in App_Start/RouteConfig.cs):
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
In addition to providing a name and URL pattern, this route also defines a set of default parameters to be used in the event that the URL fits the route pattern, but doesn’t actually provide values for every segment.
For instance, Table 1-1 contains a list of URLs that match this route pattern, along with corresponding values that the routing framework will provide for each of them.

Table 1-1. Values provided for URLs that match our route pattern
URL                                        Controller                               Action                         ID
/auctions/auction/1234             AuctionsController                      Auction              1234
/auctions/recent                        AuctionsController                      Recent
/auctions                                  AuctionsController                      Index
/                                               HomeController                         Index

·         The first URL (/auctions/auction/1234) in the table is a perfect match because it satisfies every segment of the route pattern, but as you continue down the list and remove segments from the end of the URL, you begin to see defaults filling in for values that are not provided by the URL.
·         This is a very important example of how ASP.NET MVC leverages the concept of convention over configuration: when the application starts up, ASP.NET MVC discovers all of the application’s controllers by searching through the available assemblies for classes that implement the System.Web.Mvc.IController interface (or derive from a class that implements this interface, such as System.Web.Mvc.Controller) and whose class names end with the suffix Controller.
·         When the routing framework uses this list to figure out which controllers it has access to, it chops off the Controller suffix from all of the controller class names.
·         So, whenever you need to refer to a controller, you do so by its shortened name, e.g.,  AuctionsController is referred to as Auctions, and Home Controller becomes Home.
·         What’s more, the controller and action values in a route are not case-sensitive. This means that each of these requests—/Auctions/Recent, /auctions/Recent, /auctions/recent, or even /aucTionS/rEceNt—will successfully resolve to the Recent action in the AuctionsController.
·         Note: URL route patterns are relative to the application root, so they do not need to start with a forward slash (/) or a virtual path designator (~/).
·         Route patterns that include these characters are invalid and will cause the routing system to throw an exception.
·         As you may have noticed, URL routes can contain a wealth of information that the routing engine is able to extract.
·         In order to process an ASP.NET MVC request, however, the routing engine must be able to determine two crucial pieces of information: the controller and the action.

·         The routing engine can then pass these values to the ASP.NET MVC runtime to create and execute the specified action of the appropriate controller.

Tuesday, 15 July 2014

Modifying our first MVC 4 Web Application


Apart from the generated code I’m just going to add some more pieces to this MVC Web Application. I will be publishing a full fledge ePhoneBook on ASP.NET MVC 4 later. This sample code will help you to get more understanding on MVC 4.
The first thing I’m going to do is adding a PhoneBook Model class .
Adding MVC Model
I have changed the PhoneBookModel code as below,
In this class I have mentioned the validation attribute for the elements. The ValidationAttributes are comes fromSystem.ComponentModel.DataAnnotations. There are multiple validation attributes available and all are self-descriptive.
The above image shows the available validation attributes. Read More on Validation Attribute from MSDN.
Now let’s add required views (Create, Edit, Delete, Details, List), to add the views just right click on the View folder and click on Add --> Views menu.
Now I’m going to add the Listing view, I have given the View Name as “Index” and selected the 'create a strongly typed view' Model from the Drop-down so that the code will be generated accordingly to the Model. If the created PhoneBookModel is not showing in the dropdown then build the application and then check.
select typed model - view mvc
Now we can specify which scaffolding template to use so that the code will be generated as per the template , I have selected “List” template like below
When you click on ‘OK’ button the Index.cshtml is ready.
The same way I have added all files for this sample project
The details page looks like
If you look at the code from Create template all validations are in place
Now we need to add Controller actions for these scaffolding items.
Click on the Add --->Controller menu, once you have clicked on that menu then a popup will be shown like below ,
There are multiple controller templates available in this dialogue box
  • Empty MVC controller
  • MVC controller with read/write actions and views, using Entity Framework
  • MVC controller with empty read/write actions
  • Empty API controller
  • API controller with read/write actions and views, using Entity Framework
  • API controller with empty read/write actions
I choosed “MVC controller with empty read/write actions” controller template Now give the controller name as PhoneBookController. Note that MVC requires the name of all controllers to end with "Controller".
Click on “Add” button to add the controller to our application, now the controller file is created as per our template selection and added to our project, click here to see the generated file
Now I’m going to modify the newly added controller file, the first thing I have added a property that will have a default values for the ePhoneBook
After that I have modified the Created method same as below,
Create Action MVC
If you see this method the return type is ActionResult, What’’s ActionResult. An action result represents a command that the framework will perform on behalf of the action method. The ActionResult class is the base class for action results. It Encapsulates the result of an action method and is used to perform a framework-level operation on behalf of the action method.
  • ContentResult
  • EmptyResult
  • FileResult
    • FileContentResult
    • FilePathResult
    • FileStreamResult
  • HttpUnauthorizedResult
    • HttpUnauthorizedResult
    • HttpNotFoundResult
  • JavaScriptResult
  • JsonResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase
  • PartialViewResult
  • ViewResult
Read more from MSDN
lets come back to our application, The same way I have updated the Edit also
The above code will return the data for selected entry by the mobile number, Onceyou click on update button in edit page the below method will get called
For the “Delete” method we don’t have any special User Interface that’s whyonce the entry is deleted we are returning the “Index”view.
Delete Action MVC
The “Details” method is written as below
The “Index” page will display the data from the below code
Layout menu mvc
I have added a menu for Phone Book in _Layout.cshtml. Once this all done let’s “Run” our modified application,
When you click on the “Create New” the below page will be shown
Edit page looks like below, all validations are working as per the validation attributesin model.