Wednesday, 1 March 2017

Questions

Attribute Routing in ASP.NET MVC 5


  • Routing is how ASP.NET MVC matches a URI to an action. MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application.
  • The earlier style of routing, called convention-based routing, is still fully supported. In fact, you can combine both techniques in the same project.

Why Attribute Routing?

For example, a socially enhanced e-commerce website could have the following routes:
  • {productId:int}/{productTitle} 
    Mapped to ProductsController.Show(int id)
  • {username} 
    Mapped to ProfilesController.Show(string username)
  • {username}/catalogs/{catalogId:int}/{catalogTitle} 
    Mapped to CatalogsController.Show(string username, int catalogId)
(Don’t mind the specific syntax right now, we will touch on this later.)   
In previous version of ASP.NET MVC, the rules would be set in the RouteConfig.cs file, and point to the actual controller actions, as such:
  • routes.MapRoute(
  •     name: “ProductPage”,
  •     url: “{productId}/{productTitle}”,
  •     defaults: new { controller = “Products”, action = “Show” },
  •     constraints: new { productId = “\\d+” }
  • );

When the route definitions are co-located with the actions, within the same source file rather than being declared on an external configuration class, it can make it easier to reason about the mapping between URIs and actions. The previous route definition would be set using the following, simple attribute:
  • [Route(“{productId:int}/{productTitle}”)]
  • public ActionResult Show(int productId) { … }



Enabling Attribute Routing

To enable attribute routing, call MapMvcAttributeRoutes during configuration.
  • public class RouteConfig
  • {
  •     public static void RegisterRoutes(RouteCollection routes)
  •     {
  •         routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
  •  
  •         routes.MapMvcAttributeRoutes();
  •     }
  • }

You can also combine attribute routing with convention-based routing.
  • public static void RegisterRoutes(RouteCollection routes)
  • {
  •     routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
  •  
  •     routes.MapMvcAttributeRoutes();
  •  
  •     routes.MapRoute(
  •         name: “Default”,
  •         url: “{controller}/{action}/{id}”,
  •         defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
  •     );
  • }



Custom HTML Helpers In MVC


HTML helper is a method that returns a HTML string. Then this string is rendered in view.
 MVC provides many HTML helper methods. It also provides facility to create your own
 HTML helper methods. Once you create your helper method
you can reuse it many times.

There are two ways in MVC to create custom Html helpers as below.
  1. Adding extension method for HtmlHelper class
  2. Using static method
Adding extension method for HtmlHelper classWe can create our own HTML helper by
writing extension method for HTML helper class. These helpers are available to Helper
property of class and you can use then just like inbuilt helpers.

ExampleAdd new class in MVC application and give it meaningful name. In this example
 we create new folder “CustomHelper” in application and then we add class “CustomHelpers”
 in that folder. As we are going to create extension method make this class static.
Write the following code in class:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace CustomeHelper.CustomHelper  
  8. {  
  9.     public static class CustomHelpers  
  10.     {  
  11.         public static IHtmlString File(this HtmlHelper helper, string id)  
  12.       {  
  13.             TagBuilder tb = new TagBuilder("input");  
  14.             tb.Attributes.Add("type""file");  
  15.             tb.Attributes.Add("id", id);  
  16.             return new MvcHtmlString(tb.ToString());  
  17.         }  
  18.     }  
  19. }  
In above code we create static method file for HtmlHelper class. In this method
 we create html tag with the help of TagBulider class. In this code we just use 
two attributes you can add more html attributes as per your requirement.
 Now we use this html helper method on view just like inbuilt helpers. 
As this class resides in “CustomHelper” namespace we should add this
 namespace in view as below,
  1. @using CustomeHelper.CustomHelper  
  2. @ {  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.   
  6. < h2 > Index < /h2>  
If you want to use these helpers on multiple views then add namespace in web.config file. 
Once you add that namespace you are ready to use “File” helper like below,

file

Add this method and pass id parameter. And run your view, you will get output as below.

output

Using static methodIn this method we don’t create any extension method for
 HtmlHelper class. We create new class as “CustomHelper”. 
Write the following code in class:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace CustomeHelper.CustomHelper  
  8. {  
  9.     public class CustomHelper  
  10.     {  
  11.         public static IHtmlString File(string id)  
  12.       {  
  13.             TagBuilder tb = new TagBuilder("input");  
  14.             tb.Attributes.Add("type""file");  
  15.             tb.Attributes.Add("id", id);  
  16.             return new MvcHtmlString(tb.ToString());  
  17.         }  
  18.     }  
  19. }  
Once you create this you are able to use this helper method on view. As in this method
 we don’t create extension method for HtmlHelper class, we don’t use like inbuilt helpers.
 To use this helper we use class name instead of “@Html” (in razor view) like below.

class

Add this method and pass id parameter. And run your view, you will get output as below.

output

--------------------------------------------------------------------------------------------------------------------------
1) overload controller methods in ASP.NET MVC?
Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism. HTTP works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.
In order to fix the same we need to use "ActionName" attribute.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult LoadCustomer()
        {
            return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
        public ActionResult LoadCustomer(string str)
        {
            return Content("LoadCustomer with a string");
        }
    }
So now if you make a call to URL "Customer/LoadCustomer" the "LoadCustomer" action will be invoked and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.
enter image description here
enter image description here

2) Difference between hashtable and dictionary
A) .The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys.
   .Temporary tables are a useful tool in SQL Server provided to allow for short term use of data. There are two types of temporary table in SQL Server, local and global.

3) Difference between Unique and primary key 

Primary Key

  • Primary key cannot have a NULL value.
  • Each table can have only one primary key.
  • By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.
  • Primary key can be related with another table's as a Foreign Key.
  • We can generated ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value.

Unique Key

  • Unique Constraint may have a NULL value.
  • Each table can have more than one Unique Constraint.
  • By default, Unique key is a unique non-clustered index.
  • Unique Constraint can not be related with another table's as a Foreign Key.
  • Unique Constraint doesn't supports Auto Increment value

Foreign Key

  • Foreign key is a field in the table that is primary key in another table.
  • Foreign key can accept multiple null value.
  • Foreign key do not automatically create an index, clustered or non-clustered. You can manually create an index on foreign key.
  • We can have more than one foreign key in a table.

4) Group By Department and get number of employees present in that department
A) var groupedEmploeesByDepartment = empdep.GroupBy(x => x.Department)
                                           .Select(x => new { Department = x.Key, EmployeesCount = x.Count() });


1 comment:

  1. Superb i really enjoyed very much with this article here. Really its a amazing article i had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.

    Best Dental Clinic In Chennai

    Best Dental Clinic In Tambaram

    ReplyDelete