ViewBag - 转换为html实体

时间:2012-11-29 17:29:47

标签: c# .net

我正在尝试将查询结果转换为json。

    string esql = "select d.dpr_ts, d.dpr_close from Entities3.dpr_mm as d";//where dpr_qot_id=2029543939 and dpr_ts>='" + start + "' and  dpr_ts<='" + end + "'";
    EntityConnection econn = new EntityConnection("name=Entities3");

    econn.Open();

    EntityCommand ecmd = econn.CreateCommand();
    ecmd.CommandText = esql;
    EntityDataReader ereader = ecmd.ExecuteReader(CommandBehavior.SequentialAccess);
    Console.WriteLine("Entity SQL Result");
    StringBuilder result = new StringBuilder();
    int i = 0;
    while (ereader.Read())
    {
        if (i > 0) result.Append(","); i++;
        result.Append("['" + ereader.GetDateTime(0).ToShortDateString() + "'," + ereader.GetValue(1) + "]");
    }
    ViewBag.ChartData = "[" + result.ToString() + "]";

我想将它保存在ViewBag中。但结果字符串如下所示:[&#39;10.01.2011&#39;,3,9990],[&#39;11.01.2011&#39;](因此"'"转换为&#39;)。我怎么能避免它?

顺便说一下:我能否更好地完成这项任务?

1 个答案:

答案 0 :(得分:3)

  1. 将结果从sql转换为对象,即使动态对象也可以工作。
  2. 将对象放入ViewBag
  3. 视图中的
  4. 使用Json.Net
  5. 将对象呈现为JSON

    这是一个例子

    控制器

    var data = GetDataFromDatabaseAndMapToObject();
    ViewBag.TheData = data;
    
    return View(model);
    

    视图

    <script type="text/javascript">
        var json = @Html.Raw(JsonConvert.Serilaized(ViewBag.TheData));
        //use json however you would like.
    </script>