BjarkeCK
BjarkeCK

Reputation: 5729

Can these simple HtmlHelpers be optimized?

I have these to Helper Methods:

@AdminHelper.BeginLeftMenu()

    <a href="#">content</a>

@AdminHelper.EndLeftMenu()

Is it possible to make it look more like:

@AdminHelper.LeftMenu() {

    <a href="#">content</a>

}

Instead, and what would it looke like in c#?

Upvotes: 0

Views: 140

Answers (2)

A P
A P

Reputation: 315

Two ways you can handle this.

1) You can create Extension method to HtmlHelper as below.

 public static MvcHtmlString CreateListLink(this HtmlHelper helper, string href, string linkName)
    {
       return new MvcHtmlString(string.Format("<li><a href=\"{0}\">{1}</a></li>", href, linkName));                    
    }

and you can use it as below

@Html.CreateListLink("javascript:alert('yada yada yada')", "Test Me")

Which will generate html text like this

<li>
    <a href="javascript:alert('yada yada yada')">Test Me</a>
</li>

2) You can be more fancy with new features of Asp.net MVC and use @helper razor syntax

@helper MyHelper(string href, string linkName){          
        <li><a href="@href">@linkName</a></li>;          
      }
 @MyHelper("javascript:alert('I am from razor..!!')", "hi")

You can also create App_Code folder and all extention.cshtml under that folder and add above helper in the file.

More Details: http://www.asp.net/mvc/videos/mvc-3/mvc-3-razor-helpers

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

How about making it look like this:

@using (Html.BeginLeftMenu())
{
    <a href="#">content</a>
}

which would generate for example:

<li>
    <a href="#">content</a>
</li>

You could have implemented it like this:

public static class HtmlHelperExtensions
{
    private class Menu : IDisposable
    {
        private readonly TextWriter _writer;
        public Menu(TextWriter writer)
        {
            _writer = writer;
        }

        public void Dispose()
        {
            _writer.Write("</li>");
        }
    }

    public static IDisposable BeginLeftMenu(this HtmlHelper htmlHelper)
    {
        var writer = htmlHelper.ViewContext.Writer;
        writer.Write("<li>");
        return new Menu(writer);
    }
}

Upvotes: 4

Related Questions