Monday, March 16, 2015

ASP.NET MVC: Html Helper Method

Html Helper:
  • To add content to VIEW of Asp.net MVC application, Html Helper is being used.
  • This is nothing but a method which returns string.
  • Html Helper could we used to generate standard HTML elements like Text Box, Label etc.
  • All Html helper are called on the Html property of view. For example to render a Text Box we call Html.TextBox() method.
  • Using Html helper method is optional. Its purpose is to reduce scripting code.
The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):
  • Html.ActionLink()
  •  Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()
Creating Html Helper method

Custom Html Helper method could we created in two ways
  1. Using static method.
  2. By extension method.
Using static method:
The easiest way to create custom Html helper method is create static method and return a string. Here we are going to create a Html helper method, which will render a label element of Html.

Step 1:

Add a new folder called Helpers in Asp.Net MVC application. 

Step 2:

Add a class in newly created Helpers folder. Right click at folder and then add class namedLableHelper.cs
ViewHelper.gif

Step 3:
Now add static method in this class called Label. This method will return string and will take two string parameters named target and text. 
Code will be like below

using System;using System.Collections.Generic;using System.Linq;using System.Web;
namespace MvcApplication2.Helpers
{
    public class LabelHelper    {
        public static string Label(string target, string text)
        {
            return String.Format("<label for= '{0}'>{1}</label>",target,text);
        }
    }
}


Step 4:

Now, we are going to use Label Html helper in view or aspx page. 

View\Home\Index.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"Inherits="System.Web.Mvc.ViewPage" %><%@ Import Namespace="MvcApplication2.Helpers" %><asp:Content ID="indexHead" ContentPlaceHolderID="head" runat="server">    <title>Home Page</title></asp:Content>
 <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">    <h2><%= Html.Encode(ViewData["Message"]) %></h2>    <p>        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>    <div>    <%using(Html.BeginForm())
      { %> 
        
        <%=LabelHelper.Label("firstName","Firstname"%>    
        
      <% } %>    </div>
</asp:Content>

In above code couples of things are worth noticing.
  1. We have included Namespace for Html Handler method of Label.
  2. Html.BeginForm is inside using , such that after rendering form will get closed.
  3. LabelHelper.Label is preceded by <%=.
As Extension method:
       public static class LabelExtensions
        {            public static string Label(this HtmlHelper helper, string target, string text)
            {                return String.Format("<label for='{0}'>{1}</label>", target, text);
            }
        }
In above code fact noticing are
  1. First parameter to Html Helper method is this . In case of extension method always first parameter is class on which we are extending the method.
  2. Extended method enables us to add new method in existing class.
  3. Here class is static class. We must define Extension method with static class.
  4. Extension method will be read be Intellisense like other method of the class.

Reference:http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/html-helper-method-in-Asp-Net-mvc-application/

ASP.NET MVC : DropDownList Helper Data Binding in MVC

In this article you will learn how to bind data to a DropDownList helper in MVC. We will try binding data to a DropDownList from a List<SelectListItem>, a List<Model> and also from a database.

I've created three DDL helpers on the view page and to bind each DDL we will use a different approach.


Let's bind each DDL using various approaches.

1st Approach

In this approach, I am going to bind a Country DDL with List<SelectListItem> data; here is the code I'm using in the action method.


Notice two things in above code

First: I have created a List<SelectListItem> that is IEnumerable<SelectListItem> and adding 3 items to the country object. The IEnumerable<SelectListItem> created above is added to the ViewBag with the name Country. This is how we pass the IEnumerable<SelectListItem> implicitly to the DDL helper shown below.

@Html.DropDownList("Country"String.Empty)

In the above code, the helper accepts two parameters. The first parameter named DDL ("Country") is a compulsory parameter and it should be similar to the ViewBag (ViewBag.Country) name and the second, optionLabel, is not compulsory. The optionLabel is generally used the for first option in DDL. For example, if I use:

@Html.DropDownList("Country""Select Country")

Then, it will render the following output.


Second: We can pass the IEnumerable<SelectListItem> explicitly to the DropDownList helper or we can add the IEnumerable<SelectListItem> to the ViewBag using the same name for the SelectListItem as the model property, look at the code how four different overloads are arranged.



2nd Approach

In this approach, I am going to bind Language DDL with List<Gender> data. Here the Gender is a predefined model; here is the code I'm using in the action method.


In the above code, rather than add data in country.Add(new SelectListItem { Text = "", Value = "", Selected = "" }), I'm adding to Gender properties that are Id and Name.

3rd Approach

In this approach, I am going to bind Gender DDL with database data.


Again, the database has two fields, Id and Name. The Name field is for a data value field and data text field. "Male" will be the pre-selected value in the DDL.

Complete Action Method Code

Now let me put all the above approaches in the same action method.


Complete View Page Code

I created a quick form and placed all three DDL helpers inside, when the user clicks the submit button the form data will be passed to the POST version of the DDLBinding action method that will be in the Home controller. By default, the Html.BeginForm overload takes no parameters. The no parameter version defaults to posting the form data to the POST version of the same action method and controller.


Now, when the user clicks on the submit button the HTTP POST will execute and the selected items will be passed to the DDLBinding action method that has a POST version with a query string.



Here is the POST version of the DDLBinding action method:


Hope this helps.

Reference:http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/dropdownlist-helper-data-binding-in-mvc/

Sunday, February 2, 2014

ASP.NET MVC4: Dependency Injection in ASP.NET MVC 4 using Unity IoC Container

As you know, in MVC, Controller depends on Model for data processing or you can say for executing business logic. This article will explain you how can you decouple model layers from the controller layer in an ASP.NET MVC application using Unit DI Container.

Step 1 - Create a new Asp.Net MVC4 Project

First step is to create a new Asp.Net MVC4 Project using Visual Studio 2012 or 2010SP1 as shown below:

Step 2- Install Unity Container

Now install Unity.Mvc4 Container using NuGet Package Manager Console tool as shown below:
You can also do online search for Unity.Mvc4 Container by navigating to Tools=>Extension and Update..=>Online options in Visual Studio 2012 or 2010SP1 and install it.
When it will be installed successfully, you will be find the following two references add to your project and a Bootstrapper.cs class file at project level, as shown below:
  1. using System.Web.Mvc;
  2. using Microsoft.Practices.Unity;
  3. using Unity.Mvc4;
  4.  
  5. namespace MvcNUnit
  6. {
  7. public static class Bootstrapper
  8. {
  9. public static IUnityContainer Initialise()
  10. {
  11. var container = BuildUnityContainer();
  12. DependencyResolver.SetResolver(new UnityDependencyResolver(container));
  13. return container;
  14. }
  15. private static IUnityContainer BuildUnityContainer()
  16. {
  17. var container = new UnityContainer();
  18. // register all your components with the container here
  19. // it is NOT necessary to register your controllers
  20. // e.g. container.RegisterType<ITestService, TestService>();
  21. RegisterTypes(container);
  22. return container;
  23. }
  24. public static void RegisterTypes(IUnityContainer container)
  25. {
  26. }
  27. }
  28. }

Step 3- Add a New Service Layer

Add a new Folder in the project of the name Repository and add the following interface and a class in this folder:
  1. //Product.cs
  2. public class Product
  3. {
  4. public int Id { get; set; }
  5. public string Name { get; set; }
  6. public string Category { get; set; }
  7. public decimal Price { get; set; }
  8. }
  9.  
  10. //IProductRepository.cs
  11. public interface IProductRepository
  12. {
  13. IEnumerable<Product> GetAll();
  14. Product Get(int id);
  15. Product Add(Product item);
  16. bool Update(Product item);
  17. bool Delete(int id);
  18. }
  19.  
  20. //ProductRepository.cs
  21. public class ProductRepository : IProductRepository
  22. {
  23. private List<Product> products = new List<Product>();
  24. private int _nextId = 1;
  25.  
  26. public ProductRepository()
  27. {
  28. // Add products for the Demonstration
  29. Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
  30. Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
  31. Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });
  32. }
  33.  
  34. public IEnumerable GetAll()
  35. {
  36. // TO DO : Code to get the list of all the records in database
  37. return products;
  38. }
  39. public Product Get(int id)
  40. {
  41. // TO DO : Code to find a record in database
  42. return products.Find(p => p.Id == id);
  43. }
  44. public Product Add(Product item)
  45. {
  46. if (item == null)
  47. {
  48. throw new ArgumentNullException("item");
  49. }
  50. // TO DO : Code to save record into database
  51. item.Id = _nextId++;
  52. products.Add(item);
  53. return item;
  54. }
  55. public bool Update(Product item)
  56. {
  57. if (item == null)
  58. {
  59. throw new ArgumentNullException("item");
  60. }
  61. // TO DO : Code to update record into database
  62. int index = products.FindIndex(p => p.Id == item.Id);
  63. if (index == -1)
  64. {
  65. return false;
  66. }
  67. products.RemoveAt(index);
  68. products.Add(item);
  69. return true;
  70. }
  71. public bool Delete(int id)
  72. {
  73. // TO DO : Code to remove the records from database
  74. products.RemoveAll(p => p.Id == id);
  75. return true;
  76. }
  77. }
The above repository acts as a new layer and will be used to decouple the model layer from the controller layer.

Step 4- Register the Dependency in Bootstrapper.cs file

Replace BuildUnityContainer method's content with the following code that registers the ProductRepository Service. You can also register the Product Controller in which we will inject the dependency, but it is optional.
  1. private static IUnityContainer BuildUnityContainer()
  2. {
  3. var container = new UnityContainer();
  4.  
  5. // register all your components with the container here
  6. // it is NOT necessary to register your controllers
  7.  
  8. container.RegisterType<IProductRepository, ProductRepository>();
  9. // e.g. container.RegisterType<ITestService, TestService>();
  10. RegisterTypes(container);
  11.  
  12. return container;
  13. }

Step 5- Inject Service to Controller

Now inject the dependency for the IProductRepository interface using the Product Controller's constructor as shown below:
  1. public class ProductController : Controller
  2. {
  3. readonly IProductRepository repository;
  4.  
  5. //inject dependency
  6. public ProductController(IProductRepository repository)
  7. {
  8. this.repository = repository;
  9. }
  10.  
  11. public ActionResult Index()
  12. {
  13. var data = repository.GetAll();
  14. return View(data);
  15. }
  16. //Other Code
  17. }

Step 6 – Setup Dependency Injection with Unity in Global.asax.cs

Now, setup the Bootstrapper class with in the Application_Start method so that it can initialize all dependencies. This will be done by calling Initialise() method of the Bootstrapper class as shown below:
  1. protected void Application_Start()
  2. {
  3. AreaRegistration.RegisterAllAreas();
  4.  
  5. WebApiConfig.Register(GlobalConfiguration.Configuration);
  6. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
  7. RouteConfig.RegisterRoutes(RouteTable.Routes);
  8. BundleConfig.RegisterBundles(BundleTable.Bundles);
  9. AuthConfig.RegisterAuth();
  10. //Setup DI
  11. Bootstrapper.Initialise();
  12. }

Step 7- Run the Application and see how it works

What do you think?
I hope you will enjoy the tips while programming with Asp.Net MVC4. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Other example
http://johnnewcombe.net/blog/post/13
http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-dependency-injection
 
Reference:
http://www.dotnet-tricks.com/Tutorial/dependencyinjection/632V140413-Dependency-Injection-in-ASP.NET-MVC-4-using-Unity-IoC-Container.html?goback=%2Egde_4540873_member_232971819