asp.net MVC

How to convert datatable to html table in c#?

How to convert datatable to html table in c#?, someone asked me to explain?

In this article I will show you how to convert datatable to html table by parse and generate and return as Json result in c# asp.net Mvc.

Here we converted dataset to xml and return the ajax json result and looped to form as HTML table.

Database:

Here I am using Northwind database. You can download it from following link.

Download Northwind Database

Open Microsoft sql management studio and right click on the database and attach it.

Step 1: Create an ado.net entity data model using table Employees and generate entity for that.

Step 2: Right clicks on the "Controllers" folder and add "Employee" controller. Copy and paste the following code.

public class EmployeeController : Controller
    {
       //
        // GET: /Employee/
        models db = new models();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetEmployees()
        {
            DataSet ds = new DataSet();
            string constr =db.Database.Connection.ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Employees"))
                {
                   cmd.Connection = con;
                   
                   using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                   {
                       da.Fill(ds, "Employees");
                   }
               }
            }
            return new JsonResult
            {
               Data = new
               {
                   success = ds.GetXml(),
                   message = "Success",
               },
               JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }

Step 3: Right click on the "Index" action method in the "EmployeeController" and add "Index" view. Copy and paste the following code.

@{
   ViewBag.Title = "Howto convert datatable to html table in c#?";
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax({
           type: "POST",
            url:"@Url.Action("GetEmployees", "Employee", new { area = "" })",
           data: '{}',
           contentType: "application/json;charset=utf-8",
           dataType: "json",
           success: OnSuccess,
           failure: function (response) {
                debugger;
               alert(response.success);
            },
           error: function (response) {
               alert(response.success);
            }
        });
    });
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.success);
        var xml = $(xmlDoc);
        var customers = xml.find("Employees");
        var table = $("#dvEmployees table").eq(0).clone(true);
        $("#dvEmployees table").eq(0).remove();
       $(customers).each(function () {
            $(".name", table).html($(this).find("FirstName").text() + "" + $(this).find("LastName").text());
            $(".city", table).html($(this).find("City").text());
            $(".postal", table).html($(this).find("PostalCode").text());
            $(".country", table).html($(this).find("Country").text());
            $(".Homephone", table).html($(this).find("HomePhone").text());
            $("#dvEmployees").append(table).append("<br />");
           table = $("#dvEmployeestable").eq(0).clone(true);
        });
    }
</script>
<style type="text/css">
    body {
        font-family: Arial;
        font-size: 10pt;
    }
 
    table {
        border: 1px solid #ccc;
        border-collapse: collapse;
        background-color: #fff;
        width: 200px;
    }
 
        table th {
            background-color: #B8DBFD;
            color: #333;
            font-weight: bold;
        }
 
        table th, table td {
            padding: 5px;
            border: 1px solid #ccc;
        }
 
        table, table table td {
            border: 0px solid #ccc;
        }
</style>
<h2>How to convert datatable to htmltable in c#?</h2>
<div>
    <div id="dvEmployees">
        <table class="tblEmployee" cellpadding="2" cellspacing="0" border="1">
            <tr>
                <th>
                   <b><u><span class="name"></span></u></b>
                </th>
            </tr>
            <tr>
                <td>
                   <b>City: </b><span class="city"></span>
                   <br />
                   <b>Postal Code: </b><span class="postal"></span>
                   <br />
                   <b>Country: </b><span class="country"></span>
                   <br />
                   <b>Home Phone: </b><span class="Homephone"></span>
                   <br />
                </td>
            </tr>
        </table>
    </div>
</div>

Output:

How to convert datatable to html table in c#?

Post your comments / questions