【发布时间】:2018-03-14 00:48:37
【问题描述】:
您好,我正在使用 ASP.NET 和 razor 在 VS 中工作,尝试使用 db 表中的值填充表,但我必须将 Json 解码或解析为简单文本。我真的很感激一些帮助。 这就是我得到的。
[HttpGet]
public ActionResult GetData()
{
string stdb = "Data Source=DMX87025;Initial Catalog=DB_PCC;Integrated Security=True";
SqlConnection conn = new SqlConnection(stdb);
string sql = "SELECT *FROM[DB_PCC].[dbo].[Departments]";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
var st = "kyo please help me u.u";
return Json(new { success = true, message = rd },
JsonRequestBehavior.AllowGet);
}
<div id="result"></div>
<input type="button" name="name" value="try" onclick="DepListQuery()" />
<script>
function DepListQuery() {
$.ajax({
type: 'GET',
url: '@Url.Action("GetData","Home")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#result').text(response.message);
},
failure: function (response) {
alert("something get wrong u.u");
}
});
}
</script>
【问题讨论】:
-
您需要读取
ExecuteReader()之后的数据并转换为模型并返回该模型的集合,然后在脚本中循环遍历该集合。 -
SqlDataReader rd = cmd.ExecuteReader();然后设置message = rd。您需要执行rd.Read()来获取字符串。
标签: javascript c# ajax asp.net-mvc