Tag Archives: ajax

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.

Rotating content with JQuery, JTemplates & AJAX

The following JavaScript is used here to rotate the featured product every 30 seconds. I will leave the implementation of the JSON-emitting REST api for another post.

<!--mce:0-->
<!--mce:1-->    
 
<!--mce:2-->
<div class="outerbox"></div>
<textarea> 
&lt;div class="outerbox"&gt;
&lt;div class="box featured"&gt;
&lt;h2 &gt;
			Featured&lt;/h2&gt;
&lt;div class="item"&gt;
&lt;div class="bord-se"&gt;
&lt;div class="bord-ne"&gt;
&lt;div class="bord-s"&gt;
						&lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" id="A1"&gt;
							&lt;img class="FeaturedProduct" src="{$T.ThumbnailUrl}" mce_src="{$T.ThumbnailUrl}" alt="featured" style="border-width:0px;" mce_style="border-width: 0px;" /&gt;
						&lt;/a&gt;
					&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h4&gt;
			&lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget"&gt;{$T.Name}&lt;/a&gt;&lt;/h4&gt;
 
			&lt;span&gt;Author: &lt;/span&gt;
			&lt;a href="/store/search.aspx?m={$T.AuthorId}" mce_href="/store/search.aspx?m={$T.AuthorId}"&gt;{$T.Author}&lt;/a&gt; 
			&lt;span class="Price"&gt;
				${$T.Price}&lt;/span&gt; 
 
            {$T.Summary}				
 
			&lt;a class="more" href="/store/New-Products-C52.aspx" mce_href="/store/New-Products-C52.aspx"&gt;view all…&lt;/a&gt;
 
&lt;/div&gt;
&lt;/div&gt;
 
</textarea>