Introduction

This article explains how to retreive values from a database using a Stored Procedure and bind the data to a DataTable using a MVC Razor view.

Step 1

Create a table as in the following:

query

Step 2

Create a Stored Procedure as in the following:

result

Stored Procedure

  1. create proc sp_s_Reg
  2. as
  3. begin
  4. select UserID,Username,Password,FullName,EmailID from Registration1
  5. end

Step 3

Create a project. Go to File, then New and click Project. Select ASP.NET MVC 4 Web Application and enter the project name, then click OK, select Empty, select View Engine Razor and press OK.

Step 4

Add the Entity model as in the following:

add new item

ado dot net

select data connection

table

navigation properties

Step 5

Add a Controller as in the following:

add controller

Home controller.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace MvcDatatable.Controllers {
  7. public class HomeController: Controller {
  8. //
  9. // GET: /Home/
  10. public ActionResult Index() {
  11. RBACEntities r = new RBACEntities();
  12. var data = r.sp_s_Reg().ToList();
  13. ViewBag.userdetails = data;
  14. return View();
  15. }
  16. }
  17. }

Step 6

Add a View as in the following:

add view

Index .cshtml

  1. @{
  2. ViewBag.Title = "Show Database value in DataTable";
  3. }
  4. <h2>Show Database value in DataTable</h2>
  5. <div>
  6. <table id="t01">
  7. <thead>
  8. <th>UserID</th>
  9. <th>Username</th>
  10. <th>Password</th>
  11. <th>FullName</th>
  12. <th>EmailID</th>
  13. </thead>
  14. @foreach (var item in ViewBag.userdetails)
  15. {
  16. <tr>
  17. <td>
  18. @item.UserID
  19. </td>
  20. <td>
  21. @item.Username
  22. </td>
  23. <td>
  24. @item.Password
  25. </td>
  26. <td>
  27. @item.FullName
  28. </td>
  29. <td>
  30. @item.EmailID
  31. </td>
  32. </tr>
  33. }
  34. </table>
  35. </div>
  36. <style>
  37. table#t01 {
  38. width: 100%;
  39. background-color: #f1f1c1;
  40. }
  41. table#t01 tr:nth-child(even) {
  42. background-color: #eee;
  43. }
  44. table#t01 tr:nth-child(odd) {
  45. background-color: #fff;
  46. }
  47. table#t01 th {
  48. color: white;
  49. background-color:blue;
  50. }
  51. table, th, td {
  52. border: 1px solid black;
  53. }
  54. table, th, td {
  55. border: 1px solid black;
  56. border-collapse: collapse;
  57. }
  58. table, th, td {
  59. border: 1px solid black;
  60. border-collapse: collapse;
  61. }
  62. th, td {
  63. padding: 15px;
  64. }
  65. </style>

Step 7

Run the project.

view in browser

show output