0

我只想返回 messageID 但它不能正常工作。如何返回单个字符串值?

    [WebMethod]
    public string messageComeGetID(string from, string to)
    {
        try
        {
            sqlConn.Open();
        }
        catch (Exception e)
        {
            return null;
        }
        // select messageID from tblMessage where [from] = '2' AND [to] = '4' gibi.
        SqlCommand cmd3 = new SqlCommand("select messageID from tblMessage where [from]=@from AND [to]=@to", sqlConn);

        cmd3.Parameters.AddWithValue("@from", from);
        cmd3.Parameters.AddWithValue("@to", to);

        cmd3.Connection = sqlConn;
        object value = cmd3.ExecuteScalar();
        string messageID = Convert.ToString(value);
        cmd3.ExecuteNonQuery();
        cmd3.Dispose();
        sqlConn.Close(); 

        return messageID;
    }
4

1 回答 1

1

我可以这样实现 WebService1.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace StackOverflow_Solve.Services
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetMessage()   // Home.CS 
        {
            //return "GOGO";
            Context.Response.Output.Write("Hello World");
            Context.Response.End();
            return string.Empty;
        } 
    }
}

全面实施是

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<head> //HTML and Ajax 
<title></title>

 <script>
     function GetMessage() {
         //Load jQuery($) to Use 
         $(function() {
             $.get("WebService1.asmx/GetMessage", function (data) {
                 console.log(data);
                 $("p").html(data);
             });
         });

     }
 </script>
</head>
<body>
    <input type="button" onclick="GetMessage()" value="Get Message" />
    <p></p>
</body>
</body>
</html>
于 2016-09-28T06:12:27.840 回答