2015-02-09 154 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文件上按一下按鈕,保存數據