ASP.Net - Json webmethod导致更加丰富

时间:2014-03-16 15:37:14

标签: c# asp.net json webmethod

我试图从浏览器调用json webmethod(存在于代码隐藏文件中)。 但是没有输出!

在我的json.aspx.cs页面中:网络方法是

[System.Web.Script.Services.ScriptService]
        public class _default : System.Web.Services.WebService
        {
            [WebMethod]
            [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
            public string[] UserDetails()
            {
                return new string[] { "abc", "def" };
            }
        }

当我从浏览器中尝试以下网址时:

http://www.mydomain/json.aspx/UserDetails

我没有结果! (页面是空白的)我希望 - 浏览器显示 - {“abc”,“def”}

如果我做错了,请纠正我。我的目的是在浏览器中将结果作为纯文本。如果我将webmethod放在后面的代码中,是不是可以实现?我不想为此创建单独的服务......

3 个答案:

答案 0 :(得分:1)

_default真的是这个类的名称,这只是示例中的一个错误吗?它应该不是json吗?

    [System.Web.Script.Services.ScriptService]
    public class Json : System.Web.Services.WebService
    {

答案 1 :(得分:0)

页面上需要一个脚本管理器:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

然后你可以这样调用你的函数:

// hook this up to a button click
function Test()
{
    PageMethods.UserDetails(Success);
}

// this is the callback from the page
function Success(Data)
{
    alert(Data);
}

答案 2 :(得分:0)

实际上以上都没有。

现在我不再使用网络表单代码,而是创建了一个新的asmx页面&amp;把它放在后面的代码中 现在,它显示了一些配置问题: 为了解决这个问题,我补充道:

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>

............

在你的配置文件中。

现在我在浏览器中获取输出。

现在唯一剩下的就是 - 我想把它作为纯文本(json)。

但是我把它作为xml:

<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>abc</string>
<string>def</string>
</ArrayOfString>

我也想解决这个问题。