将LINQ查询结果存储为JSON对象并传递给javascript

时间:2011-06-15 03:10:08

标签: jquery asp.net ajax json

我有一个查询,我添加到列表中。现在我需要在javascript中使用它。它正在ASP.NET 3.5中完成。所以,我需要将它作为JSON对象发送。这就是我所做的:(我不确定这是否是获取JSON对象的正确方法。如果我错了,请纠正我。

    List<NCDCPoint> dupli = (from n in CDC.NCDCPoints
                             where n.EVENT_TYPE_ID == et
                             where n.BeginDate == b
                             where n.EndDate == e
                             select n).ToList<NCDCPoint>();
  System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
 new System.Web.Script.Serialization.JavaScriptSerializer();
   string sJSON = oSerializer.Serialize(dupli); 





} 

这就是我的jquery看起来的样子

   $.ajax({
            type: "POST", url: "Data.aspx/CheckInsertRecord",
            data: "{EventType:'" + eventtype + "',BeginDate:'" + begindate + "'," +
                   "EndDate:'" + enddate+"' }",
            contentType: "application/json; charset=utf-8", dataType: "json",
            success: function (msg) {
            alert(msg.d);
            if(msg.d == "true")
        {
        Showduplicate();
        }
            }
        });

那么,请告诉我接下来需要做什么?还有一件事是我已经将true或false返回到aspx页面中的$ .ajax {}。那么我应该如何发送JSON对象?

3 个答案:

答案 0 :(得分:0)

如果你刚刚开始,那么你最好从一开始就使用ASP.NET MVC,它比传统的ASP.NET Web Forms要好得多。当您这样做时,您想要创建一个返回JsonResult的操作方法。这是一篇很好的文章,可以帮助您入门。

http://msmvps.com/blogs/shahed/archive/2009/08/23/asp-net-asp-net-mvc-tips-json-handler-aspx-template-asynchronous-jquery-treeview-with-ashx-generic-handler-and-many-more.aspx

答案 1 :(得分:0)

将您的方法更改为返回List<NCDCPoint>并将返回类型声明为json:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json]
public static List<NCDCPoint> CheckInsertRecord(String EventType, String BeginDate, String EndDate)
{
    NCDCPoint ncdc = new NCDCPoint();
    CEOSurveyDataContext CDC = new CEOSurveyDataContext();
    int et = Convert.ToInt32(EventType);


    DateTime b = Convert.ToDateTime(BeginDate);
   DateTime e = Convert.ToDateTime(EndDate);

        bool query = ( from n in CDC.NCDCPoints
                      where n.EVENT_TYPE_ID == et
                      where n.BeginDate == b
                      where n.EndDate == e
                      select n).Count()>0;

    return = (from n in CDC.NCDCPoints
                             where n.EVENT_TYPE_ID == et
                             where n.BeginDate == b
                             where n.EndDate == e
                             select n).ToList<NCDCPoint>();
} 

答案 2 :(得分:0)

您可以使用JavascriptSerializer序列化对象并发送。

var dupli= from n in CDC.NCDCPoints
                         where n.EVENT_TYPE_ID == et
                         where n.BeginDate == b
                         where n.EndDate == e
                         select n;

return new JavaScriptSerializer().Serialize(dupli);

在jquery ajax的成功回调中。

...
success:function(msg){
var data = $.parseJSON(msg.d);
//And you get your object
}