views:

43

answers:

1

Is there a way to make helper in Asp.Net MVC to wrap other html like this:

<div class="lightGreyBar_left">
    <div class="lightGreyBar_right">

        <!--Content-->
        <h3>
            Profiles</h3>
        <div class="divOption">
            <%= Html.ActionLinkWithImage("Create new", "add.png", Keys.Actions.CreateProfile, "add")%>
        </div>
        <!--Content-->

    </div>
</div>

So that helper will render containing divs and content that is passed to helper method as parameter.

+1  A: 

Have a look at the forms helper methods. They provide syntax like this:

<% using (Html.BeginForm()) { %>
    <p>Form contents go here.</p>
<% } %>

The pattern for implementing this sort of HTML helpers is slightly more involved than the usual "just return a HTML string" type helpers. Basically, your helper method will Response.Write the opening tag(s) when it is called and return some custom object that implements IDisposable. When the return value is disposed, it should Response.Write the closing tag(s).

Here is a working example:

public static MyContainer WrapThis(this HtmlHelper html)
{
    html.ViewContext.HttpContext.Response.Write("<div><div>");
    return new MvcDocument(html.ViewContext.HttpContext.Response);
}

public class MyContainer : IDisposable
{
    readonly HttpResponseBase _httpResponse;
    bool _disposed;

    public MvcDocument(HttpResponseBase httpResponse)
    {
        _httpResponse = httpResponse;
    }

    public void Dispose()
    {
        if (!_disposed)
        {
            _disposed = true;
            _httpResponse.Write("</div></div>");
        }

        GC.SuppressFinalize(this);
    }
}

This will allow you to rewrite your view to this:

<% using (Html.WrapThis()) { %>
    <h3>Profiles</h3>
    <div class="divOption">
        <%= Html.ActionLinkWithImage("Create new", "add.png", Keys.Actions.CreateProfile, "add")%>
    </div>
<% } %>
Jørn Schou-Rode