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.
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"})%>
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.
精彩评论