Reputation: 276
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. 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 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>
Upvotes: 0
Views: 965
Reputation: 1402
First thing you need to fix is how you read data from the SqlDataReader
. Here is a tutorial on doing so: 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();
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:
How to parse JSON list of string on ajax return?
List of Objects To Json String
I also want to note that you should surround your SqlConnection
, SqlCommand
, SqlDataReader
, etc with using
blocks.
Upvotes: 1