-->

How to retrieve database data & show in a view using jquery in an ASP.Net MVC.




Introduction

In this post, I am explain How to retrieve database data & show in a view using jquery in an ASP.Net MVC.
Here is this post, I have used jquery for fetch data from database. I have used $.ajax method of Jquery for hit Action of a controller, which return json data.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "UserController"

Step-6: Add new action into your controller for Get view

Here I have added "GetUser" Action into "User" Controller. Please write this following code

  1. namespace MVCFetchDataJquery.Controllers
  2. {
  3. public class UserController : Controller
  4. {
  5. public ActionResult GetUser()
  6. {
  7. return View();
  8. }
  9. }
  10. }

Step-7: Add another action into your controller for Get All data from Jquery

Here I have added "GetAllUser" Action into "User" Controller. Please write this following code

  1. public JsonResult GetAllUser()
  2. {
  3. List<UserMaster> allUser = new List<UserMaster>();
  4.  
  5.  
  6. // Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
  7. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  8. {
  9. allUser = dc.UserMasters.ToList();
  10. }
  11.  
  12. return new JsonResult { Data=allUser, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  13. }

Step-8: Add another action into your controller for Get filter data from Jquery

Here I have added "GetUserWithParameter" Action into "User" Controller. Please write this following code

  1. public JsonResult GetUserWithParameter(string prefix)
  2. {
  3. List<UserMaster> allUser = new List<UserMaster>();
  4.  
  5.  
  6. // Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
  7.  
  8. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  9. {
  10. allUser = dc.UserMasters.Where(a => a.Username.Contains(prefix)).ToList();
  11. }
  12.  
  13. return new JsonResult { Data = allUser, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
  14. }

Step-9: Add view for your Action & design for fetch/show data in view (using jquery).

Right Click on Action Method (here right click on GetUser action) > Add View... > Enter View Name > Select View Engine (Razor) >Add.
HTML Code
  1. @{
  2. ViewBag.Title = "Get User";
  3. }
  4.  
  5. <h2>Get User</h2>
  6. <table>
  7. <tr>
  8. <td>
  9. Search : <input type="text" id="txtSearch" /> <input type="button" value="Search" id="btnSearch" />
  10. <input type="button" value="Get All User" id="btnAllUser" />
  11. </td>
  12. </tr>
  13. <tr>
  14. <td>
  15. <div id="UpdatePanel">
  16.  
  17. </div>
  18. </td>
  19. </tr>
  20. </table>

Step-10: Write Jquery code for fetch and show Data in a view

Write this code below your view
JS Code
  1. @section Scripts{
  2. <script>
  3. $(document).ready(function () {
  4.  
  5. // This is for Get All Data
  6. $("#btnAllUser").click(function () {
  7.  
  8. $.ajax({
  9. url: "@Url.Action("GetAllUser","User")",
  10. data: "",
  11. type: "GET",
  12. dataType: "json",
  13. success: function (data) {
  14. loadData(data);
  15. },
  16. error: function () {
  17. alert("Failed! Please try again.");
  18. }
  19. });
  20.  
  21. });
  22.  
  23. // this will use for Get Data based on parameter
  24. $("#btnSearch").click(function () {
  25. $.ajax({
  26. url: "@Url.Action("GetUserWithParameter","User")",
  27. data: { prefix: $('#txtSearch').val() },
  28. type: "GET",
  29. dataType: "json",
  30. success: function (data) {
  31. loadData(data);
  32. },
  33. error: function () {
  34. alert("Failed! Please try again.");
  35. }
  36. });
  37. });
  38.  
  39. function loadData(data) {
  40. // Here we will format & load/show data
  41. var tab = $('<table class="myTable"></table>');
  42. var thead = $('<thead></thead>');
  43. thead.append('<th>User ID</th>');
  44. thead.append('<th>Username</th>');
  45. thead.append('<th>Full Name</th>');
  46. thead.append('<th>Email ID</th>');
  47. thead.append('<th>Is Active</th>');
  48.  
  49. tab.append(thead);
  50. $.each(data, function (i, val) {
  51. // Append database data here
  52. var trow = $('<tr></tr>');
  53. trow.append('<td>' + val.UserID + '</td>');
  54. trow.append('<td>' + val.Username + '</td>');
  55. trow.append('<td>' + val.FullName + '</td>');
  56. trow.append('<td>' + val.EmailID + '</td>');
  57. trow.append('<td>' + val.IsActive + '</td>');
  58. tab.append(trow);
  59. });
  60. $("tr:odd", tab).css('background-color', '#C4C4C4');
  61. $("#UpdatePanel").html(tab);
  62. };
  63.  
  64. });
  65. </script>
  66. }

Here is the layout page

Layout Page
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>@ViewBag.Title - My ASP.NET MVC Application</title>
  6. <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
  7. <meta name="viewport" content="width=device-width" />
  8. @Styles.Render("~/Content/css")
  9. @Scripts.Render("~/bundles/modernizr")
  10. </head>
  11. <body>
  12. <header>
  13. <div class="content-wrapper">
  14. <div class="float-left">
  15. <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
  16. </div>
  17. <div class="float-right">
  18. <section id="login">
  19. @Html.Partial("_LoginPartial")
  20. </section>
  21. <nav>
  22. <ul id="menu">
  23. <li>@Html.ActionLink("Home", "Index", "Home")</li>
  24. <li>@Html.ActionLink("About", "About", "Home")</li>
  25. <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  26. </ul>
  27. </nav>
  28. </div>
  29. </div>
  30. </header>
  31. <div id="body">
  32. @RenderSection("featured", required: false)
  33. <section class="content-wrapper main-content clear-fix">
  34. @RenderBody()
  35. </section>
  36. </div>
  37. <footer>
  38. <div class="content-wrapper">
  39. <div class="float-left">
  40. <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
  41. </div>
  42. </div>
  43. </footer>
  44.  
  45. @Scripts.Render("~/bundles/jquery")
  46. @RenderSection("scripts", required: false)
  47. </body>
  48. </html>
  49.  

Step-11: Run Application.


Download     Live Demo


Related Post :

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.

Related Posts: