GET, SET The Value From HTML Table In ASP.NET MVC jQuery

We are going to create an editable HTML table where we set and get the HTML table row value using Asp.Net MVC.
 
In this step-by-step walkthrough you will learn the following things,
 
Article is divided into two parts/sections
  1. Send Data From Controller To View -- Bind to HTML Table
  2. Receiving HTML Table data client side.
SEND Data to View From Controller: SECTION 1
  1. How to fetch the data from Database - SQL Server using Entity Framework?
  2. How to send list collection data to View ?
  3. How to Iterate the List Collection in View?
RECEIVED Table Data Client Side : SECTION 2
  1. How to get particular row data with different methods?
  2. Why is Method 1 better and more reliable than Method 2?
  3. How to get values of all rows of HTML table?
SECTION 1 - Start of SEND Data to View From Controller
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Default View of Solution Explorer
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
tblMembers - Table Structure
  1. USE [MbkTest]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[tblMembers]    Script Date: 12-Nov-19 7:33:53 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. SET ANSI_PADDING ON  
  12. GO  
  13.   
  14. CREATE TABLE [dbo].[tblMembers](  
  15.     [MemberID] [int] IDENTITY(1,1) NOT NULL,  
  16.     [MemberName] [varchar](50) NULL,  
  17.     [PhoneNumber] [varchar](50) NULL,  
  18. PRIMARY KEY CLUSTERED   
  19. (  
  20.     [MemberID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23.   
  24. GO  
  25.   
  26. SET ANSI_PADDING OFF  
  27. GO  
Table Sample Data View
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Now right click on project select Add New Item…
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Select EF Designer From Database then click on NEXT button
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
In below dialog box do the following things,
  • Data Source = Microsoft SQL Server.
  • Server Name = Your Sql Server detail.
  • Authentication = As per your sql server.
  • Select or Enter a database name = Select your database.
  • Click on Test Connection.
Then click on Ok button
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Select Table(s) of your choice.
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
As you click on FINISH button edmx file will be generated with selected table(s).
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
You can see in Solution Explorer window.
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Right click on CONTROLLERS folder click on ADD --> CONTROLLER…
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Default Actionmethod of HomeControllers,
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Default View - RouteConfig.cs
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
As per the above code default ActionResult “Index” is executing . Now we will change ActionResult (action) to “FriendResult”. After changing/updating the following things in RouteConfig.cs our default actionmethod is FriendResult.
 
Now it's changed to this,
 
RouteConfig.cs File Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace GetSetHtmlTableValue  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  
Now press F5, following,
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Now Update the following code to the respective files.
 
HomeController.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace GetSetHtmlTableValue.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult FriendList()  
  12.         {  
  13.             //Create Instance of EntityFramework dbContext Class  
  14.             MbkTestEntities db = new MbkTestEntities();  
  15.   
  16.             //Get all the friends  in list collection.  
  17.             var FriendList = db.tblFriends.ToList();  
  18.               
  19.             //send data to view. In view we generate html table with friend datas.  
  20.             return View(FriendList);  
  21.         }  
  22.   
  23.   
  24.         // GET: Home  
  25.         public ActionResult Index()  
  26.         {  
  27.             return View();  
  28.         }  
  29.   
  30.         // GET: Home/Details/5  
  31.         public ActionResult Details(int id)  
  32.         {  
  33.             return View();  
  34.         }  
  35.   
  36.         // GET: Home/Create  
  37.         public ActionResult Create()  
  38.         {  
  39.             return View();  
  40.         }  
  41.   
  42.         // POST: Home/Create  
  43.         [HttpPost]  
  44.         public ActionResult Create(FormCollection collection)  
  45.         {  
  46.             try  
  47.             {  
  48.                 // TODO: Add insert logic here  
  49.   
  50.                 return RedirectToAction("Index");  
  51.             }  
  52.             catch  
  53.             {  
  54.                 return View();  
  55.             }  
  56.         }  
  57.   
  58.         // GET: Home/Edit/5  
  59.         public ActionResult Edit(int id)  
  60.         {  
  61.             return View();  
  62.         }  
  63.   
  64.         // POST: Home/Edit/5  
  65.         [HttpPost]  
  66.         public ActionResult Edit(int id, FormCollection collection)  
  67.         {  
  68.             try  
  69.             {  
  70.                 // TODO: Add update logic here  
  71.   
  72.                 return RedirectToAction("Index");  
  73.             }  
  74.             catch  
  75.             {  
  76.                 return View();  
  77.             }  
  78.         }  
  79.   
  80.         // GET: Home/Delete/5  
  81.         public ActionResult Delete(int id)  
  82.         {  
  83.             return View();  
  84.         }  
  85.   
  86.         // POST: Home/Delete/5  
  87.         [HttpPost]  
  88.         public ActionResult Delete(int id, FormCollection collection)  
  89.         {  
  90.             try  
  91.             {  
  92.                 // TODO: Add delete logic here  
  93.   
  94.                 return RedirectToAction("Index");  
  95.             }  
  96.             catch  
  97.             {  
  98.                 return View();  
  99.             }  
  100.         }  
  101.     }  
  102. }  
FriendList.cshtml code
  1. @*Receiving data from Controller*@  
  2. @model IEnumerable<tblFriend>  
  3.   
  4. @*Setting Page Title*@  
  5. @{  
  6.     ViewBag.Title = "Friend List";  
  7. }  
  8.   
  9. <style>  
  10.     /* CSS for table and input (textbox) */  
  11.     table, td, th {  
  12.         border: 1px solid black;  
  13.     }  
  14.   
  15.     table, tr {  
  16.         border-collapse: collapse;  
  17.     }  
  18.   
  19.     input[type=text] {  
  20.         width: 100%;  
  21.     }  
  22.   
  23.     th {  
  24.         height: 50px;  
  25.         text-align: center;  
  26.     }  
  27. </style>  
  28.   
  29.   
  30. <h2>Friend List</h2>  
  31.   
  32. <input type="button" value="Get All Rows Data" class="btngetvalue" />  
  33. <table>  
  34.     <thead>  
  35.         <tr>  
  36.             <th>  
  37.                 FRIEND NAME  
  38.             </th>  
  39.             <th>  
  40.                 COMPANY NAME  
  41.             </th>  
  42.             <th>  
  43.                 EMAIL ID  
  44.             </th>  
  45.             <th>  
  46.                 ACTION TYPE 1  
  47.             </th>  
  48.             <th>  
  49.                 ACTION TYPE 2  
  50.             </th>  
  51.         </tr>  
  52.   
  53.     </thead>  
  54.   
  55.     <tbody>  
  56.   
  57.         @*Loop Entire Friend list and paste data to textbox(input)*@  
  58.   
  59.         @foreach (var item in Model)  
  60.         {  
  61.             //for ID purpose writing this code  
  62.             var friendid = "friend" + Convert.ToString(item.FriendID);  
  63.   
  64.             <input type="hidden" id="@friendid" value="@item.FriendID" />  
  65.   
  66.             <tr class="">  
  67.                 <td>  
  68.                     <input type="text" value="@item.FriendName" name="FriendName" />  
  69.                 </td>  
  70.                 <td>  
  71.                     <input type="text" value="@item.CompanyName"  name="CompanyName"/>  
  72.                 </td>  
  73.                 <td>  
  74.                     <input type="text" value="@item.Email" name="Email" />  
  75.                 </td>  
  76.   
  77.                 @*Html Button onclick calling UPDATEROW which passing parameter of friendid.*@  
  78.                 <td><input type="button" value="Get Row Value Type 1" class="btnrowvalue1" /> </td>  
  79.                 <td><input type="button" value="Get Row Value Type 2" class="btnrowvalue2" /> </td>  
  80.             </tr>  
  81.         }  
  82.     </tbody>  
  83.   
  84. </table>  
  85.   
  86. <label id="allrowsdata"><b>All Row Data Come Here</b></label>  
Output
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
End of SEND Data to View From Controller
 
SECTION 2 - Start of Receiving Table Data Client Side
 
To get the HTML table row value we are going to use Jquery. In this article we will learn two ways to get HTML table row value.
 
Method 1
  1. //METHOD 1 to get Table Row Value  
  2.      //Method 1 is good and reliable than Method 2  
  3.      $(".btnrowvalue1").click(function () {  
  4.          var tr = $(this).closest('tr');  
  5.          var FirstCol = tr.find('input[name="FriendName"]').val();  
  6.          var SecondCol = tr.find('input[name="CompanyName"]').val();  
  7.          var ThirdCol = tr.find('input[name="Email"]').val();  
  8.          alert('Type1 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);      
  9.      });  
In method 1 we are finding values of row columns value by column name of input element.
 
OUTPUT
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Method 2
  1. //METHOD 2 to get Table Row Value  
  2.       $(".btnrowvalue2").click(function () {  
  3.           var tr = $(this).closest('tr');  
  4.           var FirstCol = tr.find('td:eq(0) input').val();;  
  5.           var SecondCol = tr.find('td:eq(1) input').val();  
  6.           var ThirdCol = tr.find('td:eq(2) input').val();  
  7.           alert('Type2 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);  
  8.       });  
In method 2 we are finding values of row columns by column sequence number.
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
Why is Method 1  good and more reliable than Method 2?
 
Method 1 is better and more  reliable because if you change sequence of column(s) then also you will get an accurate result. In Method 1 we search / find the values on the basis of column name and in Method 2 we search / find the values on the basis of column sequence number.
 
Method 1
 
tr.find('input[name="FriendName"]').val();
 
Method 2
 
tr.find('td:eq(0) input').val();;
 
How to get values of all rows of HTML table?
  1. //Get All Rows Value of HTML Value  
  2.        $(".btngetvalue").click(function () {  
  3.            var address = [];  
  4.            $("table tr td input[type='text']").each(function () {  
  5.                var textval = $(this).val();  
  6.                address.push(textval);  
  7.            });  
  8.             var wholetabledata = address.toString();  
  9.            $("#allrowsdata").text("ALL ROWS DATA :"+"\n\n\n"+wholetabledata);  
  10.        });  
OUTPUT
 
GET, SET The Value From HTML Table In ASP.NET MVC jQuery 
 
RouteConfig.cs CODE
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace GetSetHtmlTableValue  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  
_Layout.cshtml CODE
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  7.     <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />  
  8.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />  
  9.     <script src="~/Scripts/modernizr-2.6.2.js"></script>  
  10.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  11.     <script src="~/Scripts/bootstrap.min.js"></script>  
  12. </head>  
  13. <body>  
  14.     <div class="navbar navbar-inverse navbar-fixed-top">  
  15.         <div class="container">  
  16.             <div class="navbar-header">  
  17.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  18.                     <span class="icon-bar"></span>  
  19.                     <span class="icon-bar"></span>  
  20.                     <span class="icon-bar"></span>  
  21.                 </button>  
  22.                 @Html.ActionLink("Application name""Index""Home"new { area = "" }, new { @class = "navbar-brand" })  
  23.             </div>  
  24.             <div class="navbar-collapse collapse">  
  25.                 <ul class="nav navbar-nav">  
  26.                 </ul>  
  27.             </div>  
  28.         </div>  
  29.     </div>  
  30.   
  31.     <div class="container body-content">  
  32.         @RenderBody()  
  33.         <hr />  
  34.         <footer>  
  35.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
  36.         </footer>  
  37.     </div>  
  38.   
  39. </body>  
  40. </html>  
HomeController.cs CODE
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace GetSetHtmlTableValue.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         public ActionResult FriendList()  
  12.         {  
  13.             //Create Instance of EntityFramework dbContext Class  
  14.             MbkTestEntities db = new MbkTestEntities();  
  15.   
  16.             //Get all the friends  in list collection.  
  17.             var FriendList = db.tblFriends.Take(10).ToList();  
  18.               
  19.             //send data to view. In view we generate html table with friend datas.  
  20.             return View(FriendList);  
  21.         }  
  22.   
  23.   
  24.         // GET: Home  
  25.         public ActionResult Index()  
  26.         {  
  27.             return View();  
  28.         }  
  29.   
  30.         // GET: Home/Details/5  
  31.         public ActionResult Details(int id)  
  32.         {  
  33.             return View();  
  34.         }  
  35.   
  36.         // GET: Home/Create  
  37.         public ActionResult Create()  
  38.         {  
  39.             return View();  
  40.         }  
  41.   
  42.         // POST: Home/Create  
  43.         [HttpPost]  
  44.         public ActionResult Create(FormCollection collection)  
  45.         {  
  46.             try  
  47.             {  
  48.                 // TODO: Add insert logic here  
  49.   
  50.                 return RedirectToAction("Index");  
  51.             }  
  52.             catch  
  53.             {  
  54.                 return View();  
  55.             }  
  56.         }  
  57.   
  58.         // GET: Home/Edit/5  
  59.         public ActionResult Edit(int id)  
  60.         {  
  61.             return View();  
  62.         }  
  63.   
  64.         // POST: Home/Edit/5  
  65.         [HttpPost]  
  66.         public ActionResult Edit(int id, FormCollection collection)  
  67.         {  
  68.             try  
  69.             {  
  70.                 // TODO: Add update logic here  
  71.   
  72.                 return RedirectToAction("Index");  
  73.             }  
  74.             catch  
  75.             {  
  76.                 return View();  
  77.             }  
  78.         }  
  79.   
  80.         // GET: Home/Delete/5  
  81.         public ActionResult Delete(int id)  
  82.         {  
  83.             return View();  
  84.         }  
  85.   
  86.         // POST: Home/Delete/5  
  87.         [HttpPost]  
  88.         public ActionResult Delete(int id, FormCollection collection)  
  89.         {  
  90.             try  
  91.             {  
  92.                 // TODO: Add delete logic here  
  93.   
  94.                 return RedirectToAction("Index");  
  95.             }  
  96.             catch  
  97.             {  
  98.                 return View();  
  99.             }  
  100.         }  
  101.     }  
  102. }  
FriendList.cshtml CODE
  1. @*Receiving data from Controller*@  
  2. @model IEnumerable<tblFriend>  
  3.   
  4. @*Setting Page Title*@  
  5. @{  
  6.     ViewBag.Title = "Friend List";  
  7. }  
  8.   
  9. <style>  
  10.     /* CSS for table and input (textbox) */  
  11.     table, td, th {  
  12.         border: 1px solid black;  
  13.     }  
  14.   
  15.     table, tr {  
  16.         border-collapse: collapse;  
  17.     }  
  18.   
  19.     input[type=text] {  
  20.         width: 100%;  
  21.     }  
  22.   
  23.     th {  
  24.         height: 50px;  
  25.         text-align: center;  
  26.     }  
  27. </style>  
  28. <script>  
  29.     $(document).ready(function () {  
  30.         //Get All Rows Value of HTML Value  
  31.         $(".btngetvalue").click(function () {  
  32.             var address = [];  
  33.             $("table tr td input[type='text']").each(function () {  
  34.                 var textval = $(this).val();  
  35.                 address.push(textval);  
  36.             });  
  37.              var wholetabledata = address.toString();  
  38.             $("#allrowsdata").text("ALL ROWS DATA :"+"\n\n\n"+wholetabledata);  
  39.         });  
  40.         //METHOD 1 to get Table Row Value  
  41.         //Method 1 is good and reliable  than Method 2  
  42.         $(".btnrowvalue1").click(function () {  
  43.             var tr = $(this).closest('tr');  
  44.             var FirstCol = tr.find('input[name="FriendName"]').val();  
  45.             var SecondCol = tr.find('input[name="CompanyName"]').val();  
  46.             var ThirdCol = tr.find('input[name="Email"]').val();  
  47.             alert('Type1 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);      
  48.         });  
  49.   
  50.   
  51.         //METHOD 2 to get Table Row Value  
  52.         $(".btnrowvalue2").click(function () {  
  53.             var tr = $(this).closest('tr');  
  54.             var FirstCol = tr.find('td:eq(0) input').val();;  
  55.             var SecondCol = tr.find('td:eq(1) input').val();  
  56.             var ThirdCol = tr.find('td:eq(2) input').val();  
  57.             alert('Type2 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);  
  58.         });      
  59.     });  
  60. </script>  
  61.   
  62. <h2>Friend List</h2>  
  63.   
  64. <input type="button" value="Get All Rows Data" class="btngetvalue" />  
  65. <table>  
  66.     <thead>  
  67.         <tr>  
  68.             <th>  
  69.                 FRIEND NAME  
  70.             </th>  
  71.             <th>  
  72.                 COMPANY NAME  
  73.             </th>  
  74.             <th>  
  75.                 EMAIL ID  
  76.             </th>  
  77.             <th>  
  78.                 ACTION TYPE 1  
  79.             </th>  
  80.             <th>  
  81.                 ACTION TYPE 2  
  82.             </th>  
  83.         </tr>  
  84.   
  85.     </thead>  
  86.   
  87.     <tbody>  
  88.   
  89.         @*Loop Entire Friend list and paste data to textbox(input)*@  
  90.   
  91.         @foreach (var item in Model)  
  92.         {  
  93.             //for ID purpose writing this code  
  94.             var friendid = "friend" + Convert.ToString(item.FriendID);  
  95.   
  96.             <input type="hidden" id="@friendid" value="@item.FriendID" />  
  97.   
  98.             <tr class="">  
  99.                 <td>  
  100.                     <input type="text" value="@item.FriendName" name="FriendName" />  
  101.                 </td>  
  102.                 <td>  
  103.                     <input type="text" value="@item.CompanyName"  name="CompanyName"/>  
  104.                 </td>  
  105.                 <td>  
  106.                     <input type="text" value="@item.Email" name="Email" />  
  107.                 </td>  
  108.   
  109.                 @*Html Button onclick calling UPDATEROW which passing parameter of friendid.*@  
  110.                 <td><input type="button" value="Get Row Value Type 1" class="btnrowvalue1" /> </td>  
  111.                 <td><input type="button" value="Get Row Value Type 2" class="btnrowvalue2" /> </td>  
  112.             </tr>  
  113.         }  
  114.     </tbody>  
  115.   
  116. </table>  
  117.   
  118. <label id="allrowsdata"><b>All Row Data Come Here</b></label>  
End of Receiving Table Data Client Side.
 
NEXT ARTICLE
 
In the upcoming article you will learn how to send data to Controller for Insert/update/Delete purposes.