Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Create a dynamic table when data is coming from database in MVC

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 838
    Comment on it

    In this blog, we illustrate how to create a dynamic table when data is coming from a database in MVC and display it.
    In the below example we use a dummy data and jquery to populate the HTML table.

    In controller, we have an action method called GetUsers that returns a JSON result with all the Users. This is where we can also call our repository when we want to return the users from a database:

     

    Code:

    public ActionResult GetUsers()
    {
         List<User> userList = new List<User>();
    
         User user1 = new User
         {
             UserId = 1,
              FirstName = "Anita",
              LastName = "singh"
         };
    
         User user2 = new User
         {
              UserId = 2,
              FirstName = "Ankita",
              LastName = "Rawat"
         };
    
         userList.Add(user1);
         userList.Add(user2);
    
         return Json(userList, JsonRequestBehavior.AllowGet);
    }

     

    User class

    public class User
    {
         public int UserId { get; set; }
         public string FirstName { get; set; }
         public string LastName { get; set; }
    }

     

    Code for view

    <div id="users">
         <table></table>
    </div>
    
    <script>
    
         $(document).ready(function () {
    
              var url = '/Home/GetUsers';
    
              $.getJSON(url, function (data) {
    
                 var userHeader='<tr><th> UserID</th><th>FirstName</th><th>LastName</th></tr>'
                   $.each(data, function (key, val) {
    
                        var user = '<tr><td>' + val.FirstName + '</td></tr>';
    
                        $('#users table').append(user);
    
                   });
              });
         });
    
    </script>
    

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: