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)?
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.MVCnamespace that can help you create html in code.Note: The following code hasn’t been tested.
You can call this method from the razor view like so: