Socket Extension Methods for MVC HtmlHelpers

I want to insert a set of extension methods for my MVC controllers that I want to be able to call the following template

@Html.NestedName().CustomLabelFor(m => m.Field)

      

I noticed that TwitterBootstrapMVC follows this pattern, but I have not been able to reproduce it. Can anyone show me an example of how I would structure my class extension class?

I currently have a top level class below

    public static class BootstrapHtmlHelper
{
    public static BootStrap Bootstrap(this HtmlHelper html)
    {
        return new BootStrap(html);
    }
}

      

Nested in Bootstrap class I have the following method

        public static MvcHtmlString CustomLabelFor <TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, string placeholder)
    {
        StringBuilder sb = new StringBuilder();
        return new MvcHtmlString(sb.ToString());
    }

      

Obviously it can't be static anymore, but how do I replace what would be "this" so that my method would still function? Obviously TModel and TProperty are still needed, but I'm not sure how to bring them into scope?

+3


source to share


1 answer


You're almost there. Let's break this down into two parts:

  • You need a static class to host your extension ( BootstrapHtmlHelper

    ) method .
  • You need a non-static class to host your instance method ( BootStrap

    )

So, you just need to change your second method to:

public MvcHtmlString CustomLabelFor<TProperty>(Expression<Func<TModel, TProperty>> expression, string placeholder)

      



Also, you need to change BootStrap

to keep the model type parameter passed in the extension method. So declare BootStrap

as BootStrap<TModel>

and pass this when creating a new one BootStrap

(i.e. new BootStrap<TModel>(html)

).

Now you can use it however you want:

@Html.Bootstrap().CustomLabelFor(m => m.Field)

      

(You had @Html.NestedName()

, but obviously NestedName

should have BootStrap

, since that's the name of your extension method, right?)

+3


source







All Articles