Reputation: 45
I have a database consisting a table, whose information I want to print on the browser. So what I did was:
In _Layout.cshtml:
<li class="nav-item">
<a class="nav-link" [email protected]("ViewPage1","Billing")>Records</a>
</li>
The page ViewPage1.cshtml contains:
<body>
<div>
<a [email protected]("Record_Page_Load", "Billing")>Print Records</a>
</div>
</body>
Which then calls the controller functions:
public DataTable GetRecords()
{
string constr = ConfigurationManager.ConnectionStrings["BOConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Article"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
public void Record_Page_Load()
{
DataTable dt = this.GetRecords();
StringBuilder html = new StringBuilder();
//html.Append("<html><body>");
html.Append("<table border = '1'>");
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<th>");
html.Append(column.ColumnName);
html.Append("</th>");
}
html.Append("</tr>");
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
Debug.Print(Convert.ToString(row[column.ColumnName]));
}
html.Append("</tr>");
}
html.Append("/table");
//html.Append("</body></html>");
}
public ActionResult ViewPage1()
{
return View("ViewPage1");
}
Nothing is getting printed after on clicking Print Records.
To ensure that the DataTable is indeed getting filled, I tried printing the records in the output window of Visual Studio. The data was printing. So, what is going wrong here?
Upvotes: 0
Views: 858
Reputation: 21
You're building up the html table fine as i can tell but you are not outputting it. try flusing out using context to flush out to page using context.HttpContext.Response.Write(html);
Upvotes: 1
Reputation: 77876
There are couple of mistakes as I see.
In your method Record_Page_Load()
the second loop iteration you are starting with </tr>
as seen below which should be an opening <tr>
foreach (DataRow row in dt.Rows)
{
html.Append("</tr>"); // this one
foreach (DataColumn column in dt.Columns)
{
You are not outputting the content in Response stream at all and thus nothing shows in browser.
html.Append("/table");
Response.Write(html.ToString()); // Write the content to response stream
Upvotes: 1