Reputation: 13185
I have repetitious markup for elements, like:
<div class="box">
<div class="top"></div>
<div class="content">
content goes here
</div>
<div class="bottom"></div>
</div>
Top and bottom are styled with css to include images for borders.
I could use JQuery to inject tags, but is there a better way to template controls in asp.net mvc?
Thank you
Upvotes: 1
Views: 711
Reputation: 22036
You definitely want to use an extension method to the HtmlHelper so that you can then use the notation:
<%=Html.Box("content string") %>
public static stringBox(
this HtmlHelper html,
string Content)
{
var sb = new StringBuilder();
sb.AppendLine("<div class=\"box\">");
sb.AppendLine(" <div class=\"top\"></div>");
sb.AppendLine(" <div class=\"content\">");
sb.AppendLine(Content);
sb.AppendLine(" </div>");
sb.AppendLine(" <div class=\"bottom\"></div>");
sb.AppendLine("</div>");
return sb.ToString();
}
Upvotes: 1
Reputation: 99750
There are probably a lot of ways around this, here's one:
Create a ViewUserControl (let's call it "box.ascx"):
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Action>" %>
<div class="box">
<div class="top"></div>
<div class="content">
<% Model(); %>
</div>
<div class="bottom"></div>
</div>
In your aspx, wherever you need this block, call it like this:
<% Html.RenderPartial("box", Lambda.Action(() => { %>
here comes my content! <a href="http://www.google.com">Google!</a>
<% })); %>
Here's the Lambda helper class:
public static class Lambda {
public static Action Action(Action a) {
return a;
}
}
If you don't use this little helper it will crash since it will try to cast the Action.
Upvotes: 2
Reputation: 13185
I just defined two extension methods to write the tags
public static void BeginBox(this HtmlHelper htmlHelper)
{
StringBuilder box = new StringBuilder();
box.AppendLine("<div class=\"box\">");
box.AppendLine(" <div class=\"top\"></div>");
box.AppendLine(" <div class=\"content\">");
htmlHelper.ViewContext.HttpContext.Response.Write(box.ToString());
}
public static void EndBox(this HtmlHelper htmlHelper)
{
StringBuilder box = new StringBuilder();
box.AppendLine(" </div>");
box.AppendLine(" <div class=\"bottom\"></div>");
box.AppendLine("</div>");
htmlHelper.ViewContext.HttpContext.Response.Write(box.ToString());
}
I guess this will do for now.
Upvotes: 1
Reputation: 9943
Why don't you use master pages? You can use master pages in MVC just like in ASP.Net
Upvotes: 0
Reputation: 10580
As far as I know there is no Built-In templating solution in asp.net mvc. But because the output is pure html it is very easy to do your own templating with just css and maybe a bit of JS.
Of course since everything in asp.net mvc is swappable you can replace the default view engine with one that supports templating.
Upvotes: 0