October 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Localizing, unit testing and using AJAX in ASP.NET MVC applications

  • May 26, 2009
  • By Jani Järvinen
  • Send Email »
  • More Articles »

Adding an AJAX touch to your application

Although using the latest XHTML and CSS features can get you far, using some JavaScript on the browser can bring richness to your web application. Luckily, AJAX scripts enjoy a built-in support on ASP.NET MVC, and thus more versatile user interfaces are easy to get started with.

The first thing in adding AJAX support to your ASP.NET MVC applications is to reference the proper scripts in your view pages. When you create the default ASP.NET MVC project in Visual Studio, the template creates a Scripts folder for you, with all the necessary JavaScript files already copied to the correct place. In Visual Studio's Solution Explorer, you should see several script files in this folder (Figure 5).



Click here for larger image

Figure 5. AJAX support is baked into ASP.NET MVC applications.

Although you can add custom scripts to this folder, the ones that ship with the ASP.NET MVC installation provide a convenient starting point. To get started with them, you need to reference them in your .aspx files like this:

    <script src="/Scripts/MicrosoftAjax.js"
      type="text/javascript"></script>
    <script src="/Scripts/MicrosoftMvcAjax.js"
      type="text/javascript"></script> 
  

Note how the Scripts folder contains the debug versions of these libraries. The difference is basically in the commenting, formatting and spacing of the code. Tighter spacing leads to smaller files sizes, and thus faster application loading.

With the references in place, you can use the built-in Ajax helper object to create action links that point to your controller actions, and then return data back. You can then update the user interface with this data:

  <div id="hello-world-element"></div>
<%= Ajax.ActionLink("Show Ajax Message",
  "AjaxMessage", new { Name = "TestUser" },
  new AjaxOptions {
      UpdateTargetId = "hello-world-element"
  })%> 

This code would generate a script-based link that contacts the AjaxMessage action in the Home controller. In AJAX implementations, you don't need to write any special code in the controllers: regular code that returns for instance HTML code snippets will do just fine. However, should you want to return for example objects to be manipulated with JavaScript, you could return them in JSON encoded format. ASP.NET MVC makes it easy to return such objects with the JSON helper method, accessible from the controller classes. Here is an example of such action method implementation:

  public JsonResult JsonTest()
  {
    var quickObject = new
    {
      Name = "John Doe",
      Age = 37,
      City = "Salt Lake City"
    };
    return Json(quickObject);
  }

To help writing your JavaScript code in the view pages, you can also utilize the popular jQuery library. jQuery is an open-source library (like the mock object libraries), and can be directly used from your ASP.NET MVC applications. In fact, version 1.3.2 of jQuery ships with ASP.NET MVC, and can be referenced simply by pointing to the correct .js file:

  <script type="text/javascript" src="/Scripts/jquery-1.3.2.js"></script> 

Again, after adding this reference, you can start using the library. For example, if you wanted to add some animation to your labels, you could call the fadeOut method that jQuery supports. This method takes in a timeout value in milliseconds, and then changes an HTML element's (such as one defined with the DIV tag) appearance. Here is an example:

  <script type="text/javascript">
    function FadeTextOut() {
        $("#my-id").fadeOut(1500, null);
    }
  </script>  

<a href="#" onclick="javascript:FadeTextOut();">Click me</a>
<p>
<div id="my-id" style="font-size: x-large;">Hello, World!</div>
</p>

If you are not yet familiar with jQuery, then the tutorials available at jQuery's official web site (see again the Links section) or here on Developer.com are great places to start. jQuery fans have also created nice little cheat sheets to help tackling the short function names. You might wish to grab one of these and then start exploring.

Conclusion

In this article, you learned about three different, but very common requirements for almost any ASP.NET MVC application: localization, unit testing and AJAX support. While other articles have been written about these topics before in the context of regular ASP.NET WebForms applications, ASP.NET MVC requires you to update your techniques.

For instance, localization can be done in multiple ways in ASP.NET MVC applications: just as you use resource strings, you could just as efficiently return a different view for each language. Similarly, as ASP.NET MVC applications tend not to use ScriptManager components, you need to change your tactics when writing AJAX applications.

In the end, ASP.NET MVC is a great addition to the selection of available web techniques on the Microsoft .NET platform. Although ASP.NET MVC might not be the optimal solution for every web application you build, having good skills in ASP.NET MVC will get you far.

Good luck with your development work!

Links

ASP.NET MVC 1.0 download page:
ASP.NET MVC Source Code download page:
EasyMock.NET:
Moq mock library:
Rhino Mocks:
jQuery start page:

About the Author

Jani Järvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP and a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi. His blog can be found at http://www .saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.





Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel