2

Previous to MVC, when webforms was the only thing we had, I used to define a container for my controls (A Box you may call) and used this web control (with title, body and a couple of other properties) in other controls.

So if I wanted to change the look of all my visual controls, I just had to make one change in my Box control.

Here's a simplified snippet of what I used to do:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Box.ascx.cs" Inherits="WebApp.Controls.Box" %>
<span class="boxtitle">
    <asp:Literal ID="ltrTitle" runat="server"></asp:Literal>
</span>
<div class="boxContent" id="dvBox">
    <asp:PlaceHolder runat="server" ID="BoxBodyContainer"/>
</div>

And in code-behind:

public Control BoxBody { get; set; }
public string Title
{
    get { return this.ltrTitle.Text; }
    set { this.ltrTitle.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
    this.BoxBodyContainer.Controls.Add(this.BoxBody);
}  

So I could use this along with other controls in my page as follows:

<MyControls:Box ID="Box1" Title="Foo" runat="server">
    <boxbody>
        <MyControls:CustomControl ID="Bar" runat="server" >
         </MyControls:CustomControl>
    </boxbody>
</MyControls:Box>  

In order to have something alike in MVC 3, I think I should define a Box view and wherever I need the box, use Html.Partial or Html.Action and pass all my data (title, boxbody, etc) to this view and use @Html.Raw in Box view.
But I was wondering if there's any better, more standard way to achieve this. What's the correct way of achieving this in MVC 3 (Razor)?

0

1 Answer 1

3

You can create an Html Helper extension method to do this. The best tutorial I could find was for MVC2, but it gives you the basics.

What the tutorial doesn't cover is that there are classes in the System.Web.MVC namespace that can help you create html in code.

Note: The following code hasn't been tested.

using System;
using System.Web.Mvc;

public static class HtmlExtensions
{
    public static MvcHtmlString Box(this HtmlHelper helper, string title, MvcHtmlString body)
    {
        TagBuilder span = new TagBuilder("span");
        span.AddCssClass("boxtitle");
        span.SetInnerText(title.ToString());

        TagBuilder div = new TabBuilder("div");
        div.AddCssClass("boxContent");
        div.InnerHtml = body;

        return MvcHtmlString.Create(span.ToString() + div.ToString());
    }
}

You can call this method from the razor view like so:

@Html.Box("foo", Html.Partial("bar"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This is probably the best way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.