Tag Archives: Razor

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 
        /// </summary>
        /// The helper.
        /// The content.
        /// 
        private static string RenderPartialViewTagsInTemplate(HtmlHelper helper, string content)
        {
            var controls = new Dictionary();
 
            MatchCollection matches = Regex.Matches(content, @"&lt;view: (?S+)(s+(?[^=s]+)=""?(?[^""s]+)""?)*?s*/&gt;", RegexOptions.ExplicitCapture);
 
            foreach (Match tag in matches)
            {
                string viewName = tag.Groups["name"].Value;
 
                var routeValues = new RouteValueDictionary();
 
 
                for (int i = 0; i  { content = content.Replace(c.Key, c.Value); });
 
            return content;
        }

Basic AJAX with MVC3 & Razor

Suppose you have a page which requires you to load content inline in response to some action.  In the below example, you have a filter and a “preview” button which needs to show some sample data.

You could have the button do a post and have the MVC handler parse the form fields and render the view with the data you want to show.  But, you may have a complex page with many tabs and want to optimize form performance.    In such a case, you want to send just the form data for the current tab and inject the response into the current page.  Here is how to do that:

Here is the HTML of the relevant section of the “Export” tab:

<fieldset>        
 
<div class="btn green preview">
<a href="#">Preview</a></div>
<div class="clear"></div>
 
<span>&nbsp;</span>    
</fieldset>
 
<div class="btn orange submit">
<a href="#">Export to CSV</a></div>
<div class="clear"></div>

Note the two href’s with attributes of btn.  Here is the relevant JavaScript:

$(document).ready(function () {
 
    $('.preview').click(function () {
        $('#preview').html('<strong>Loading...</strong>');
        $.post('Home/Preview/?' + $(this).closest("form").serialize(), function (data) {
            $('#preview').html(data);
        });
    });
 
    $('.submit').click(function () {
        $('.submit a').html("Loading...");
        $(this).closest("form").submit();
        return false;
    });
 
});

The “Export” button submits the entire form.  The “Preview” button on the other hand:

  1. Shows the “loading” text.
  2. Serializes the content of the parent form
  3. Posts the serialized content to a url
  4. Renders the response from that URL in the designated div

Here is Preview.cshtml:

@{
    Layout =null;
}
@model  Models.ExportFilter
 
<h2>@ViewBag.Message</h2>
 
<strong>Name, Source, Email, DateAdded</strong>
<ul>
    @foreach (var item in Model.MarketingList)
    {
	<li>@item.FirstName, @item.Source, @item.Email, @item.DateAdded.ToShortDateString()</li>
    }&nbsp;
</ul>&nbsp;

Note that I am overriding the default Layout because I don’t want to show the normal header/footer. _Blank.cshtml contains solely “@RenderBody()”

The handler for the /Preview target is:

[HttpPost]
        public ActionResult Preview(ExportFilter filter)
        {
            var export = new EmailExporter(filter);
            List emailList = export.Process();
            ViewBag.Message = string.Format("{0:##,#} records to be exported", emailList.Count); 
            return View(filter); 
        }

Now when I click “preview”, I get a momentary “loading” screen and then the rendered view.