I have a simple HTML table within a cshtml page. It is basically a single column, where I want to programmatically insert rows from the result of an ajax call.
<table class="table" id="notestedtable">
<tr>
<th>
Not Tested
</th>
</tr>
<tr>
<td>
Unit#1
</td>
</tr>
</table>
I use the document.onload = NotTested("Site 001", "17/06/2015"); to call the function which then executes the ajax.
function NotTested(SiteId,TestDate) {
$.ajax({
url: '/Home/NotTested',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify({
siteid: SiteId, testdate: TestDate
}),
success: function (result) {
for (var i = 0; i < result.Tubs.length; i++) {
alert(result.Tubs);
}
}
})
}
The returned Tubs is a string[] where Tubs[0] = "Tub 1"; Tubs[1] = "Tub 2" ... and so on. I want each of the Tub[] to form a row in my table.
This is the C# in the controller:
[HttpPost] // can be HttpGet
public ActionResult NotTested(string siteid, string testdate)
{
int i = 0;
//this could be populated first by reading for this "site" how many tubs to be expected
string[] UnTested = new string[8];
SqlConnection conn = new SqlConnection(@"Server=****;Database=****;User Id=****;Password=****;");
SqlCommand cmd = new SqlCommand("select * from TubsNotTested(@siteid,@testdate)", conn);
cmd.Parameters.AddWithValue("@siteid",siteid);
cmd.Parameters.AddWithValue("@testdate", testdate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for(i=0; i<dt.Rows.Count; i++)
{
UnTested[i] = dt.Rows[i][0].ToString();
}
return Json(new
{
Tubs = UnTested,
}, JsonRequestBehavior.AllowGet);
}