我是dot net网络服务的新手,我正在尝试以Json格式保存数据,下面是我的service.asmx文件的代码,这里我从数据库中获取数据,但我不知道'我知道如何以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 :(得分: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文件调用SaveData函数并保存数据