Render tags in templates as a partial view with MVC3
Suppose you are rendering templated content. Sometimes you want to reference partial views (or actions) in your templates and have them render with attributes provided by your template. One option is to use a Razor templating engine. But I just needed to render partial views based on a custom tag format, so I came up with my own solution:
/// <summary>
/// Render parameterized tags as a partial view in MVC3 templates
/// Supports tags such as <view:leadform citytype = AllCities coursetype = KidsOnly schooltype = KidsSchools />
/// </summary>
/// <param name = "helper">The helper.</param>
/// <param name = "content">The content.</param>
/// <returns></returns>
private static string RenderPartialViewTagsInTemplate(HtmlHelper helper, string content)
{
var controls = new Dictionary<string , string>();
MatchCollection matches = Regex.Matches(content, @"<view: (?<name>\S+)(\s+(?<attrname>[^=\s]+)=""?(?<attrvalue>[^""\s]+)""?)*?\s*/>", RegexOptions.ExplicitCapture);
foreach (Match tag in matches)
{
string viewName = tag.Groups["name"].Value;
var routeValues = new RouteValueDictionary();
for (int i = 0; i < tag.Groups["attrname"].Captures.Count; i++)
{
string key = tag.Groups["attrname"].Captures[i].Value;
string value = tag.Groups["attrvalue"].Captures[i].Value;
routeValues.Add(key, value);
}
MvcHtmlString tagHtml = new MvcHtmlString("");
try
{
tagHtml = helper.Action(viewName, routeValues);
}
catch (HttpException) // no such action, so try a view
{
tagHtml = helper.Partial(viewName, routeValues);
}
controls.Add(tag.Value, tagHtml.ToHtmlString());
}
controls.ToList().ForEach(c => { content = content.Replace(c.Key, c.Value); });
return content;
}
</attrvalue></attrname></view:></string>


Recent Comments