2015-02-09 109 views
-2

我是网络服务新手,我试图以Json格式保存数据,下面是我的service.asmx文件的代码,在这里我从数据库中获取数据,但我不知道如何以Json格式保存数据。请指导我解决这个问题。Webservice将数据保存为Json格式

using System; 
using System.Collections; 
using System.ComponentModel; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.Web.Script.Services; 
using System.Xml.Linq; 
using System.Collections.Generic; 
using System.Data.Sql; 
using System.Data.SqlClient; 

namespace JSONWeb 
{ 
    /// <summary> 
    /// Summary description for Service1 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ToolboxItem(false)] 
    [ScriptService] 

    // 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 Service1 : System.Web.Services.WebService 
    { 
     [WebMethod] 
     public DataSet SelectData() 
     { 
      SqlConnection con = new SqlConnection("Data Source=HOME;database=Data;Integrated Security=true"); 
      SqlCommand cmd = null; 
      SqlDataAdapter da; 
      DataSet ds = new DataSet(); 
      try 
      { 
       con.Open(); 
       cmd = new SqlCommand("SelectData", con); 
       cmd.CommandType = CommandType.StoredProcedure; 
       da = new SqlDataAdapter(cmd); 
       da.Fill(ds); 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 
      finally 
      { 
       con.Close(); 
      } 
      return ds; 
     } 
    } 
} 

回答

0
[WebMethod] 
    public void SaveData(string name, string address) 
    { 
     try{ 
      string connectionString =''; 
      connectionString='';//Your connection string 
      using (SqlConnection con = new SqlConnection(connectionString)) 
      { 
       //Create the SqlCommand object 
       SqlCommand cmd = new SqlCommand("usp_SaveData", con); 

       //Specify that the SqlCommand is a stored procedure 
       cmd.CommandType = System.Data.CommandType.StoredProcedure; 

       //Add the input parameters to the command object 
       cmd.Parameters.AddWithValue("@Name", name.Trim()); 
       cmd.Parameters.AddWithValue("@Address", address.Trim()); 


       //Open the connection and execute the query 
       con.Open(); 
       cmd.ExecuteNonQuery(); 
      } 
     } 
     catch(Exception ex){ 
      throw ex; 
     } 
    } 


    function SaveData(name,address) { 
     $.ajax({ 
      type: "POST", 
      url: "service.asmx/SaveData",//Give full path upto the webservice 
      data: JSON2.stringify({ name: name, address: address }), 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function(msg) { 
       alert('Data saved success'); 
      }, 
      error: function(error) { 
       alert('Data saved failed'); 
      } 

     }); 
    } 

你可以调用保存数据的功能从js文件上按一下按钮,保存数据