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.

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler