从WebMethod获取Json数据到应用程序

时间:2014-02-20 16:40:39

标签: c# asp.net ajax json web-services

我想从网络方法获取Json数据。在这里,我想得到新闻&说出这两个数据,但这里只有工作新闻。(无法获得演讲者)

这是我的存储过程

ALTER procedure [dbo].[LoadDayEvents] 
@Date date
as 
begin
select News,Speaker from Eventstbl
where DateToBePublished = CONVERT(date, @Date)
end

这是我的网络方法

 [WebMethod, ScriptMethod]
public static string SelectEventDate(string date)
{
    string News= "";
    string Speaker = "";

    try
    {
        SqlCommand comld = new SqlCommand("LoadDayEvents", conDB);
        comld.CommandType = CommandType.StoredProcedure;
        comld .Parameters.Add("@Date", SqlDbType.Date);
        comld .Parameters["@Date"].Value = DateTime.Parse(date).Date;
        if (conDB.State == ConnectionState.Closed)
            conDB.Open();
        News = comld .ExecuteScalar().ToString();
        Speaker = comld .ExecuteScalar().ToString();  // Thisone is not working
    }
    catch (Exception ee) { }
    finally { conDB.Close(); }
    return News;
}

这里我使用Ajax / Json来获取它

  <script type="text/javascript">
    $(document).ready(function () {

        var urinews = '<%= ResolveUrl("WebMethods.aspx/SelectEventDate") %>';
        var localtime = new Date();
        var today = localtime.getFullYear() + '/' + (localtime.getMonth() + 1) + '/' + localtime.getDate();


        $.ajax({
            type: "POST",
            url: urinews,
            data: "{ date: '" + today + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                $("#daily_news_Selection").append("<p>" + msg.d + "</p>");
            },
            error: function (x, e) {
            }
        });
    });
</script>

1 个答案:

答案 0 :(得分:1)

您可以返回自定义类

 var newsAndSpeaker = new NewsAndApeaker() { News = News, Speaker = Speaker}; //or define a custom class that has these two properties
 return newsAndSpeaker;

在Javascript上,您可以使用

访问这两个变量
msg.d.News //news
msg.d.Speaker

或者,您可以返回字符串列表

 var newsAndSpeaker = new List<string>() { News, Speaker}; //or define a custom class that has these two properties
 return newsAndSpeaker;

在Javascript上,您可以像数组一样访问两个变量

msg.d[0] //mews
msg.d.[1] //speaker

如果你的问题是为什么你的第二个财产没有被填充,那么标题似乎是错误的