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
- Send Data From Controller To View -- Bind to HTML Table
- Receiving HTML Table data client side.
SEND Data to View From Controller: SECTION 1
- How to fetch the data from Database - SQL Server using Entity Framework?
- How to send list collection data to View ?
- How to Iterate the List Collection in View?
RECEIVED Table Data Client Side : SECTION 2
- How to get particular row data with different methods?
- Why is Method 1 better and more reliable than Method 2?
- How to get values of all rows of HTML table?
SECTION 1 - Start of SEND Data to View From Controller
Default View of Solution Explorer
tblMembers - Table Structure
- USE [MbkTest]
- GO
-
- /****** Object: Table [dbo].[tblMembers] Script Date: 12-Nov-19 7:33:53 PM ******/
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[tblMembers](
- [MemberID] [int] IDENTITY(1,1) NOT NULL,
- [MemberName] [varchar](50) NULL,
- [PhoneNumber] [varchar](50) NULL,
- PRIMARY KEY CLUSTERED
- (
- [MemberID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- SET ANSI_PADDING OFF
- GO
Table Sample Data View
Now right click on project select Add New Item…
Select EF Designer From Database then click on NEXT button
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
Select Table(s) of your choice.
As you click on FINISH button edmx file will be generated with selected table(s).
You can see in Solution Explorer window.
Right click on CONTROLLERS folder click on ADD --> CONTROLLER…
Default Actionmethod of HomeControllers,
Default View - RouteConfig.cs
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace GetSetHtmlTableValue
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }
- );
- }
- }
- }
Now press F5, following,
Now Update the following code to the respective files.
HomeController.cs code
FriendList.cshtml code
- @*Receiving data from Controller*@
- @model IEnumerable<tblFriend>
-
- @*Setting Page Title*@
- @{
- ViewBag.Title = "Friend List";
- }
-
- <style>
-
- table, td, th {
- border: 1px solid black;
- }
-
- table, tr {
- border-collapse: collapse;
- }
-
- input[type=text] {
- width: 100%;
- }
-
- th {
- height: 50px;
- text-align: center;
- }
- </style>
-
-
- <h2>Friend List</h2>
-
- <input type="button" value="Get All Rows Data" class="btngetvalue" />
- <table>
- <thead>
- <tr>
- <th>
- FRIEND NAME
- </th>
- <th>
- COMPANY NAME
- </th>
- <th>
- EMAIL ID
- </th>
- <th>
- ACTION TYPE 1
- </th>
- <th>
- ACTION TYPE 2
- </th>
- </tr>
-
- </thead>
-
- <tbody>
-
- @*Loop Entire Friend list and paste data to textbox(input)*@
-
- @foreach (var item in Model)
- {
-
- var friendid = "friend" + Convert.ToString(item.FriendID);
-
- <input type="hidden" id="@friendid" value="@item.FriendID" />
-
- <tr class="">
- <td>
- <input type="text" value="@item.FriendName" name="FriendName" />
- </td>
- <td>
- <input type="text" value="@item.CompanyName" name="CompanyName"/>
- </td>
- <td>
- <input type="text" value="@item.Email" name="Email" />
- </td>
-
- @*Html Button onclick calling UPDATEROW which passing parameter of friendid.*@
- <td><input type="button" value="Get Row Value Type 1" class="btnrowvalue1" /> </td>
- <td><input type="button" value="Get Row Value Type 2" class="btnrowvalue2" /> </td>
- </tr>
- }
- </tbody>
-
- </table>
-
- <label id="allrowsdata"><b>All Row Data Come Here</b></label>
Output
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
-
-
- $(".btnrowvalue1").click(function () {
- var tr = $(this).closest('tr');
- var FirstCol = tr.find('input[name="FriendName"]').val();
- var SecondCol = tr.find('input[name="CompanyName"]').val();
- var ThirdCol = tr.find('input[name="Email"]').val();
- alert('Type1 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);
- });
In method 1 we are finding values of row columns value by column name of input element.
OUTPUT
Method 2
-
- $(".btnrowvalue2").click(function () {
- var tr = $(this).closest('tr');
- var FirstCol = tr.find('td:eq(0) input').val();;
- var SecondCol = tr.find('td:eq(1) input').val();
- var ThirdCol = tr.find('td:eq(2) input').val();
- alert('Type2 : ' + FirstCol + ' ' + SecondCol + ' ' + ThirdCol);
- });
In method 2 we are finding values of row columns by column sequence number.
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?
-
- $(".btngetvalue").click(function () {
- var address = [];
- $("table tr td input[type='text']").each(function () {
- var textval = $(this).val();
- address.push(textval);
- });
- var wholetabledata = address.toString();
- $("#allrowsdata").text("ALL ROWS DATA :"+"\n\n\n"+wholetabledata);
- });
OUTPUT
RouteConfig.cs CODE
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace GetSetHtmlTableValue
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "FriendList", id = UrlParameter.Optional }
- );
- }
- }
- }
_Layout.cshtml CODE
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title>
- <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
- <script src="~/Scripts/modernizr-2.6.2.js"></script>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/bootstrap.min.js"></script>
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- </ul>
- </div>
- </div>
- </div>
-
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - My ASP.NET Application</p>
- </footer>
- </div>
-
- </body>
- </html>
HomeController.cs CODE
FriendList.cshtml CODE
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.