weixin_33724059 2010-03-07 21:43 采纳率: 0%
浏览 52

ASP.NET MVC和SQL Server

I am new to ASP.NET and the MVC framework as well, so I'd love it if someone could recommend and/or show me some examples of code on how to best read a table from a database and store it as json.

The goal after that is to receive some query filter options from a javascript, and then output the json-ified table back to the javascript. This will be done for multiple tables, with different column names and different amounts of columns that need to be returned.

When I was working in regular asp.net and c# I built JSON using a stringbuilder like this;

StringBuilder json = new StringBuilder();
while (reader.Read())
{

    json.AppendFormat("{{{{\"AvgDate\": \"{0}\"}},{{\"MarkerID\": \"{1}\"}}}},", reader["AvgDate"], reader["MarkerID"]);

}

Where "AvgDate" and "MarkerID" are columns. My concern with this way of doing it is how to implement a smart way of reusing the same code for when I need more than two columns from the table.

So I would really appreciate any good input I could get here, especially if MVC has any other good way of doing it.

  • 写回答

1条回答 默认 最新

  • 程序go 2010-03-07 22:00
    关注

    Instead using a StringBuilder to create the JSON result, you could use the following approach:

    public class MyClass
    {
      public DateTime AverageDate { get; set; }
      public int MarkerId { get; set; }
    }
    
    // the action method
    
    public JsonResult MyAction()
    {
      var result = new List<MyClass>();
      //..
      while (reader.Read())
      {
        result.Add(new MyClass() {
          AverageDate = reader["AvgDate"], MarkerId = reader["MarkerId"] };
      }
      //..
      return Json(result);
    }
    

    Note: this code might not compile as-is. For a complete sample, see here for example.

    评论

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功