Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, March 24, 2013

Creating Custom HTML Helpers - ASP.NET MVC 4

What are HTML Helpers in ASP.NET MVC?

HTML Helpers are nothing but the way of rendering HTML on the view page in ASP.NET MVC. Typically what we have in traditional ASP.NET web forms is Web Controls to achieve same functionality but with the evolution of MVC pattern , you don't have any web controls to add on to the view pages.
In simple words - it is just a method which returns you a string , and string is HTML.

Example of HTML Helpers:

ASP.NET MVC framework ships with various inbuilt HTML helpers such as ActionLink , Label.
Lets take a look at how a HTML helper is added to the view page. I am considering Razor view engine for this example.


@Html.ActionLink("Display Name of Link", "MethodName", "ControllerName");

Example above shows how OOB Action Link is used to render the HTML hyperlink on the view page.

Another example is shown as below where it is used to render the Html label tag to render Store Name property of model class. 

@Html.LabelFor(model => model.StoreName)

 Why to use Html Helpers?

Question might have poped up in your mind by now that Html helpers are just going to render the string of html then why do I need to use them ? If I know the Html syntax then why not add the Html directly on to the view page? 
Answer is simple, it depends how clean and consistent you want to make your application. of course you can do the direct addition of html tags on your view pages but if you observe second example - you can see that it is simply rendering the label tag on view page for a property in model at run time. so it just for making developer's life more easy and to have the cleaner html for your view page.

Need of Custom Html Helpers?

Well, there is always need to do some custom stuff on top of what framework offers, and reason for doing this is either business requirement or to get things done in smarter way.

Writing a custom Html helper is nothing but writing an extension method. you are actually writing an extension method for HtmlHelper class.
Being a SharePoint developer I always find this task similar to creation of a web control where you override the render method of base class and do the custom Html rendering. 

Creating Custom Html Helper

All right , for demo purpose I will keep the example simple - I will simply write an Html helper which will render the header of any content on view page.
This is done simply by using the <header> tag of Html 5.

Step 1: Define your custom static class for creation of your custom Html helpers

public static class DemoCustomHtmlHelpers
{

}

Step 2: Add static method to the class and make sure that return type is MvcHtmlString. Write an input paramter of method as HtmlHelper and also a string for which the header tag needs to be generated.
You might need to add System.Web.Mvc namespace to your class.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{

          
}

Step 3 : Add the rendering logic in the method , you can take help from TagBuilder class to generate Html tags to be rendered.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{
   var tagBuilder = new TagBuilder("header");
   tagBuilder.InnerHtml = content;
   return new MvcHtmlString(tagBuilder.ToString());
}


Step 4: Build the project and open any of the view page. Now you can use your custom Html helper to render the header. Make sure that your view page has correct using namespace for using your custom Html helper extension.


@Html.Header("Create")


When you observe the view page's Html , you will be finding the generated Html tag by our Custom Html helper extension

<header>Create</header>


So this is all guys , have fun and try to create these Html Helper extensions in your scenarios.



Saturday, February 23, 2013

Passing Parameters to Events - C#

All right , again one post away from my favorite SharePoint world but this is kind of generic which can be used anywhere in C#.

Today we will see how we can pass some custom parameters to any event in C#.

Consider a scenario where you are calling some method asynchronously and execution is happening in loops.
In General, we register an event with the method which gets called after method call is completed. but as the asynchronous execution is happening in the loop , so in the on completed event you never know which for which call the execution has been completed.

Check out this sample scenario where I have a simple windows forms application with two buttons and label, both buttons are registered to a same on click event. Now say, on click of each button I want to perform some independent actions and also want to pass some parameters to the on click event. I know there can be many approaches to do this but I have just taken this example to prove the actual point of this blog post.


public Form1()
{
   InitializeComponent();

   button1.Click += new EventHandler(button_Click);
   button2.Click += new EventHandler(button_Click);
}

void button_Click(object sender, EventArgs e)
{
   label1.Text = "Hi ";
}

Now on both button clicks - the text of a label is printed as 'Hi' as the event is common between both buttons.

Now what I want is to pass some extra information to the on click event from both buttons , you can pass on any number and type of  objects as you want. for the example I will send a string and Enum to click events.

I will also need to modify the button click event , as I am going to send some parameters to event so I need to catch those in the event.

public Form1()
{
  InitializeComponent();

  button1.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is   From Button1", MessageType.B1); };

  button2.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is From Button2", MessageType.B2); };

}

void button_Click(object sender, EventArgs e, string message, MessageType type)
{
   if (type.Equals(MessageType.B1))
   {
      label1.Text = message;
   }
   else if (type.Equals(MessageType.B2))
   {
      label1.Text = message;
   }
}

enum MessageType
{
   B1,
   B2
}