Alan
Alan

Reputation: 43

Asp.Net MVC custom controls - container

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.

Upvotes: 4

Views: 1068

Answers (1)

J&#248;rn Schou-Rode
J&#248;rn Schou-Rode

Reputation: 38346

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 MyContainer(html.ViewContext.HttpContext.Response);
}

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

    public MyContainer(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>
<% } %>

Upvotes: 4

Related Questions