所以我去了这个信息,并有一个空表名类别表,所以我必须将记录存储在categoryList中,以便下面的代码可以工作。那么我在categoryList中写什么来从我的类别管理器中获取记录并显示来自sql的数据
</table>
<script>
$(document).ready(function () {
var categoryList = [];
var $courseTableElement = $('#categoryTable');
var $rowElement;
var $cellElement;
var index = 0;
for (index = 0; index < categoryList.length; index++) {
$rowElement = $('<tr></tr>');
$cellElement = $('<td></td>', { text: categoryList[index].CategoryName });
$rowElement.append($cellElement);
$cellElement = $('<td></td>', { text: categoryList[index].CategoryId });
$rowElement.append($cellElement);
$courseTableElement.append($rowElement);
}
});
</script>
public List<Category> getAllCategory(string inUserId)
{
DataSet ds = new DataSet();
List<Category> categoryList = new List<Category>();
string sqlText = "";
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn; //setup the
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
sqlText = "SELECT CategoryId,CategoryName,CreatedBy,CreatedAt,UpdatedBy,UpdatedAt " +
" FROM Category ";
cmd.CommandText = sqlText;
cmd.Parameters.Add("@inCurrentUserId", SqlDbType.VarChar, 200).Value = inUserId;
da.Fill(ds, "CategoryData");
cmd.CommandText = sqlText;
}//using SqlDataAdapter da
cn.Close();
}//using SQLCommand cmd
}//using SQLConnection cn
foreach (DataRow dr in ds.Tables["CategoryData"].Rows)
{
Category category = new Category();
category.CategoryId = Int32.Parse(dr["CategoryId"].ToString());
category.CategoryName = dr["CategoryName"].ToString();
category.CreatedBy = dr["CreatedBy"].ToString();
category.CreatedAt = DateTime.Parse(dr["CreatedAt"].ToString());
category.UpdatedBy = dr["UpdatedBy"].ToString();
category.UpdatedAt = DateTime.Parse(dr["UpdatedAt"].ToString());
categoryList.Add(category);
}
return categoryList;
}
答案 0 :(得分:0)
您只需向服务器发出ajax请求并获取该数据即可。我做了几个假设。
getAllCategory将返回正确的json。
function getDataFromServer(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get",url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
//data was retrieved successfully.
callback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.send();
}
$(document).ready(function () {
//the path to action must include the id in querystring
var url = 'path_to_action'
getDataFromServer(url, function(data){
var courseTableElement = $('#categoryTable');
for(var i = 0; i < data.length; i++){
var row = $('<tr></tr>');
var cell1 = $('<td></td>, { text: data[i].CategoryName } );
var cell2 = $('<td></td>, { text: data[i].CategoryId } );
row.append(cell1);
row.append(cell2);
courseTableElement.append(row);
}
}
});