Extension Methods in asp.net mvc
why to use extension method ?
well, in a simple statement I would say extension methods are used to get rid of writing html source code for views in asp.net mvc
let's take an example
suppose you are building a html table with several rows and cols in view
eg:
<table><tr><td>...</td></tr></table>
now you need to use table structure in various places in your application so without re writing this just create one extension method and put you structure over there
like this :
namespace ExtensionMethods.Common
{
public static class Helpers
{
public static string table(this HtmlHelper helper, string itemfirst, string itemsecond)
{
return String.Format("<table><tr><td>{0}</td></tr><tr><td>{1}</td></tr></table>", itemfirst, itemsecond);
}
}
}
note:static class only can have static functions.
so now when you implement table structure into your view,you just need to add appropriate namespace for my case this was
"ExtensionMethods.Common".
as shown below :
Now whenever you need this structure just imports the appropriate namespace and then call extension method by passing parameters within it.
and you will see items witin table structure in your application.












0 comments:
Post a Comment