ASP.NET MVC和SQL Server


                    

我也是ASP.NET和MVC框架的新手,所以如果有人可以推荐和/或向我展示一些有关如何最好地从数据库读取表并将其存储为的代码示例,我将非常喜欢它。 json。</ p>

此后的目标是从javascript接收一些查询过滤器选项,然后将json-ified表输出回javascript。 这将针对多个表完成,这些表具有不同的列名和需要返回的不同列数。</ p>

当我在常规的asp.net和c#中工作时,我使用像这样的stringbuilder构建了JSON; </ p>

  StringBuilder json =新的StringBuilder();
而(reader.Read())
{

     json.AppendFormat(“ {{{{\” AvgDate \“:\” {0} \“}},{{\” MarkerID \“:\” {1} \“}}}},”,读者[“ AvgDate“],阅读器[” MarkerID“]));

}
</ code> </ pre>

其中“ AvgDate”和“ MarkerID”为列。 我对此的关注方式是,当我需要从表中获取两列以上时,如何实现一种巧妙的方法来重用同一代码。</ p>

因此,我非常感谢我能在这里得到的任何宝贵意见,尤其是如果MVC还有其他好的做法。</ p>
     </ div>

展开原文

原文

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个回答


您可以使用以下方法代替使用StringBuilder创建JSON结果:</ p>

 公共类MyClass
{
   公开的DateTime AverageDate {get; 组; }
   public int MarkerId {get; 组; }
}

//动作方法

公共JsonResult MyAction()
{
   var result = new List ();
   // ..
   而(reader.Read())
   {
     result.Add(new MyClass(){
       AverageDate = reader [“ AvgDate”],MarkerId = reader [“ MarkerId”]};
   }
   // ..
   返回Json(result);
}
</ code> </ pre>

注意:此代码可能无法按原样编译。 有关完整示例,请在此处查看< / a>。</ p>
     </ div>

展开原文

原文

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.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐