views:

33

answers:

2

I'm new to asp.net mvc. I'm looking to create some control for reusing html. I have a complex HTML box for example:

<div class="Box">
    <div class="Top"></div>
    <div class="Content">
        <div style="padding:10px;">
        [CONTENT GOES HERE]
        </div>
    </div>
    <div class="Bottom"></div>
</div>

Previously using webforms I've been able to reuse this by inheriting from WebControl and override Render. But how can I implement this in MVC?

The Content of the box could of course be what ever. Other boxes for example.

+2  A: 

Easiest yet: using a UserControl

<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl" %>
<div class="Box">
    <div class="Top"></div>
    <div class="Content">
        <div style="padding:10px;">
        <%= Model.Content %>
        </div>
    </div>
    <div class="Bottom"></div>
</div>

And then calling the user control with

<% Html.RenderPartial("NiceBox", New with {.Content = "The real content goes here"})%>
Eduardo Molteni
Is this method useful if let's say I want to put an entire form inside the box? I'm entirely clear about the "with {.Content..." part.
ZNS
Oh, I see your point now. This approach is more useful to structured content. You can still use WebControls in MVC as long as they do not rely on `PostBack` or `ViewState`
Eduardo Molteni
So I can implement a webcontrol into a view in the same way as in a weboform? <prefix:name runat="server">stuff goes here</prefix:name> ?
ZNS
@ZNS: yes, of course
Eduardo Molteni
A: 

Here's an example of one way to build it as an HtmlHelper extension method:

    public static string Box(this HtmlHelper helper, string content)
    {
        var builder = new StringBuilder();
        builder.Append("<div class=\"Box\" .......... );

        if (!String.IsNullOrEmpty(content))
        {
            builder.Append(content)
        }

        return builder.ToString();    
    }

In your view:

  <%= Html.Box(contentString) %>

Your other options are to create it as a partial view (.ascx) and pass it a ViewModel class that contained the content that you wanted to render. Judging by the requirement of "the content could be anything", an HtmlHelper extension might be more flexible for you.

womp