[英]Parsing JSON data ASP.NET C# and Razor
Hi I'm working in VS with ASP.NET and razor, trying to fill a table with values from a db table but I have to decode or parse Json to simple text. 嗨,我正在使用ASP.NET和razor在VS中工作,试图用db表中的值填充表,但我必须将Json解码或解析为简单文本。 I really appreciate some help.
我真的很感谢您的帮助。 This is what i´m getting.
这就是我得到的。
[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 uu"; 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 uu"); } }); } </script>
First thing you need to fix is how you read data from the SqlDataReader
. 您需要解决的第一件事是如何从
SqlDataReader
读取数据。 Here is a tutorial on doing so: http://csharp-station.com/Tutorial/AdoDotNet/Lesson04 这是有关此操作的教程: http : //csharp-station.com/Tutorial/AdoDotNet/Lesson04
But even better would be to read data directly into objects. 但更好的方法是将数据直接读入对象。 See this answer for details on creating such extension methods: Convert rows from a data reader into typed results
有关创建此类扩展方法的详细信息,请参见此答案: 将数据读取器中的行转换为键入的结果
The sample extension method: 样本扩展方法:
public static List<T> ReadList<T>(this IDataReader reader,
Func<IDataRecord, T> generator) {
var list = new List<T>();
while (reader.Read())
list.Add(generator(reader));
return list;
}
After your SqlDataReader rd = cmd.ExecuteReader();
在您的
SqlDataReader rd = cmd.ExecuteReader();
line, you'd need something like: 行,您将需要以下内容:
var departmentList = reader.ReadList(x => new Department {
DeptID = x.GetInt32(0),
DeptName = x.GetString(1)
});
Then, once you have such a list of objects, you can return them to the front-end view ajax: 然后,一旦有了这样的对象列表,就可以将它们返回到前端视图ajax:
How to parse JSON list of string on ajax return? 如何在ajax返回上解析字符串的JSON列表?
List of Objects To Json String Json字符串的对象列表
I also want to note that you should surround your SqlConnection
, SqlCommand
, SqlDataReader
, etc with using
blocks. 我还想指出,您应该
using
块包围SqlConnection
, SqlCommand
, SqlDataReader
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.