我正在尝试使用ajax调用填充页面,并且只在我成功调用ajax时获取sql
语句。
我的方法是:
$('#news-search').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/news.aspx/NewsSearch',
data: JSON.stringify({
title: $('#txt_newsSearch').val()
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function(msg) {
console.log(msg.d);
},
error: function (err, jqXHR) {
console.log(jqXHR);
console.log(err);
}
});
});
我在后面的代码中调用了一个webmethod:
[System.Web.Services.WebMethod]
public static string NewsSearch(string title)
{
var obj = new NewsSearch();
using (var db = new DbDataContext())
{
var q = db.News.Where(x => x.NewsTitle.Contains(title)).Select(x => new
{
x.Article,
x.NewsTitle,
x.PublishDate
});
return q.ToString();
}
}
我创建了一个名为NewsSearch
的类,其中包含我想要恢复的属性,我尝试在select中分配,但我不能。
如何获取成功调用返回的属性?
此时将其返回控制台。
SELECT [t0].[Article], [t0].[NewsTitle], [t0].[PublishDate]
FROM [dbo].[News] AS [t0]
WHERE [t0].[NewsTitle] LIKE @p0
答案 0 :(得分:1)
以下代码将以JSON格式返回NewsSearch对象:
public class NewsSearchResult
{
public string Article;
public string NewsTitle;
public DateTime PublishDate;
}
public class NewsSearch
{
public List<NewsSearchResult> Results;
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static NewsSearch NewsSearch(string title)
{
var obj = new NewsSearch();
using (var db = new DbDataContext())
{
var q = db.News.Where(x => x.NewsTitle.Contains(title)).Select(x => new NewsSearchResult
{
Article = x.Article,
NewsTitle = x.NewsTitle,
PublishDate = x.PublishDate,
});
obj.Results = q.ToList();
}
return obj;
}
答案 1 :(得分:0)
您必须序列化结果,否则您将获得linq查询。
[System.Web.Services.WebMethod]
public static string NewsSearch(string title)
{
var obj = new NewsSearch();
using (var db = new DbDataContext())
{
var q = db.News.Where(x => x.NewsTitle.Contains(title)).Select(x => new
{
x.Article,
x.NewsTitle,
x.PublishDate
});
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(q.ToArray());
}
}
不要忘记包含名称空间System.Web.Script.Serialization
查看代码项目文章Example Of JavaScript Serializer And Json String Using WebMethod