How to Implement jQuery Accordion in ASP.Net MVC

It is very straight forward to implement a jQuery accordion in ASP.Net MVC. If we need to implement any jQuery UI widgets in ASP.NET MVC there there is no need to do any extra work. This is a cool feature of ASP.Net MVC.

localhost

Let's see with one simple ASP.NET MVC 4 application.

  • Step 1

    Create a blank ASP.NET MVC application.
  • Step 2

    Download the jQuery and jQuery UI libray fron Nuget Package Manager in the application.

  • Step 3

    Create the Home Controller like this:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6.   
    7. namespace MvcApplication8.Controllers  
    8. {  
    9.     public class HomeController : Controller  
    10.     {  
    11.         //  
    12.         // GET: /Home/  
    13.   
    14.         public ActionResult Index()  
    15.         {  
    16.             return View();  
    17.         }  
    18.   
    19.     }  
    20. }  
  • Step 4

    Create the Index view and implement the jQuery and style sheet as in this code snippet.
    1. @{  
    2.     ViewBag.Title = "Index";  
    3. }  
    4.   
    5. <script src="~/Scripts/jquery-2.1.1.min.js"></script>  
    6. <script src="~/Scripts/jquery-ui-1.11.2.min.js"></script>  
    7. <link href="~/Content/themes/base/all.css" rel="stylesheet" />  
    8. <link href="~/Content/themes/base/accordion.css" rel="stylesheet" />  
    9. <link href="~/Content/demos.css" rel="stylesheet" />  
    10.   
    11. <script type="text/javascript">  
    12.     $(function () {  
    13.         $("#accordion").accordion();  
    14.     });  
    15. </script>  
    16.   
    17. <div class="demo">  
    18. <div id="accordion">  
    19.   <h3>This is the Title1</h3>  
    20.   <div>  
    21.     <p>  
    22.     Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer  
    23.     ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit  
    24.     amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut  
    25.     odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.  
    26.     </p>  
    27.   </div>  
    28.   <h3>This is the Title2</h3>  
    29.   <div>  
    30.     <p>  
    31.     Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet  
    32.     purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor  
    33.     velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In  
    34.     suscipit faucibus urna.  
    35.     </p>  
    36.   </div>  
    37.     
    38. </div>  
    39.   
    40. </div>  
Summary

Here I have not done any extra work to implement this functionality so ASP.NET MVC is very convenient with the jQuery UI Library. This is one of the good features of ASP.NET MVC.


Similar Articles