[英]string sent to a webmethod with json/ajax
i have a ajax call sending some data to a webmethod (c#) from a aspx page and one of the parameters sent is some free text comments. 我有一个ajax调用,它从aspx页面向webmethod(c#)发送一些数据,并且发送的参数之一是一些自由文本注释。 now i have noticed some errors and the updates dont get made to the database. 现在我注意到一些错误,并且没有对数据库进行更新。 So with some checking out i believe its slashes and 's and probably other characters doing causing this. 因此,在进行了一些检查后,我相信它的斜线和以及其他字符确实引起了这种情况。 i tried using escape() method and it works, but then adds all sorts of encoded text to the database which i dont want. 我尝试使用escape()方法,它可以工作,但是随后将各种编码的文本添加到我不想要的数据库中。 Im not a greatly experienced coder so i know there is some sort of encoding to do here, but how im not sure. 我不是一个经验丰富的编码员,所以我知道这里可以做某种编码,但是我不确定。 here is the ajax below that works until i get slashes and 这是下面的ajax,直到我得到斜线和
$("#btnEditFields").click(function () {
//Store the New comment
var strSupplierOrderNo = $("#<%=tbPopUpEditSuppOrdNo.ClientID%>").val();
var strComment = $("#<%=tbPopUpEditComments.ClientID%>").val();
var strCurrentStage = $("#<%=ddlPopUpEditCurrentStage.ClientID%>").val();
var strReviewDate = $("#<%=tbPopUpEditReviewDate.ClientID%>").val();
var strOrderDate = $("#<%=tbPopUpEditOrderDate.ClientID%>").val();
var strRequiredLive = $("#<%=tbPopUpEditRequiredLiveDate.ClientID%>").val();
var strActualAppointmentDate = $("#<%=tbPopUpEditActualAppointmentDate.ClientID%>").val();
var strOtherRef = $("#<%=tbPopUpFieldOtherRef.ClientID%>").val();
var EditRecordArgs = (strServiceID + "," + strSupplierOrderNo + "," + strComment + "," + strCurrentStage + "," + strReviewDate + "," + strOrderDate + "," + strRequiredLive + "," + strActualAppointmentDate + "," + strOtherRef);
//alert(addNewCommentArgs);
// Confirming the operation from the user
if (confirm("You are about to add a new comment to order " + strPSTNNum + "?")) {
$.ajax({
type: "POST",
//UpdateRecordInGridViewUsingAjax.aspx is the page name and UpdateOrder
// is the server side web method which actually does the updation
url: "PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB",
//Passing the record id and data to be updated which is in the variable update_data
data: "{'args': '" + EditRecordArgs + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
//Giving message to user on successful updation
success: function () {
alert("Comment successfully added!!!");
location.reload();
},
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
}
return false;
});
});
Here Is the web method: 这是网络方法:
[System.Web.Services.WebMethod]
public static void updatePSTNDataInDB(string args)
{
string[] data = args.Trim().Split(',');
string strServiceID = data[0];
string strSupplierOrderNo = data[1];
string strComment = data[2];
string strCurrentStage = data[3];
string strReviewDate = data[4];
string strOrderDate = data[5];
string strRequiredLive = data[6];
string strActualAppointmentDate = data[7];
string strOtherRef = data[8];
#region Check for and existing PSTNReport Record and create one if not, then run the update to the database.
SqlConnection seConnection1 = new SqlConnection();
seConnection1.ConnectionString = Databases.getDbConnectionString("csSingleEnded2");
seConnection1.Open();
SqlCommand seCmd1 = new SqlCommand("CheckForPSTNReportRecord", seConnection1);
seCmd1.CommandType = CommandType.StoredProcedure;
seCmd1.Parameters.Add(new SqlParameter("@ServiceID", SqlDbType.Int));
seCmd1.Parameters["@ServiceID"].Value = strServiceID;
SqlDataAdapter dbAdapter1 = new SqlDataAdapter(seCmd1);
DataSet dbSeDataset1 = new DataSet();
dbAdapter1.Fill(dbSeDataset1);
if (dbSeDataset1.Tables[0].Rows.Count == 0)
{
SqlCommand seCmd2 = new SqlCommand("AddAPSTNReportRecord", seConnection1);
//specify that the command is a sproc and not just SQL text
seCmd2.CommandType = CommandType.StoredProcedure;
//Create the parameters
seCmd2.Parameters.Add(new SqlParameter("@ServiceID", SqlDbType.Int));
seCmd2.Parameters["@ServiceID"].Value = strServiceID;
SqlDataAdapter dbAdapter2 = new SqlDataAdapter(seCmd2);
DataSet dbSeDataset2 = new DataSet();
dbAdapter2.Fill(dbSeDataset2);
seConnection1.Close();
}
SqlConnection seConnection = new SqlConnection();
seConnection.ConnectionString = Databases.getDbConnectionString("csSingleEnded2");
seConnection.Open();
SqlCommand seCmd = new SqlCommand("UpdatePstnOrdersComments", seConnection);
seCmd.CommandType = CommandType.StoredProcedure;
seCmd.Parameters.Add(new SqlParameter("@ServiceID", SqlDbType.Int));
seCmd.Parameters.Add(new SqlParameter("@SupplierOrderNumber", SqlDbType.NVarChar,50));
seCmd.Parameters.Add(new SqlParameter("@Comments", SqlDbType.NVarChar,4000));
seCmd.Parameters.Add(new SqlParameter("@OrderDate", SqlDbType.DateTime));
seCmd.Parameters.Add(new SqlParameter("@RequiredLiveDate", SqlDbType.DateTime));
seCmd.Parameters.Add(new SqlParameter("@AppointmentDate", SqlDbType.DateTime));
seCmd.Parameters.Add(new SqlParameter("@ReviewDate", SqlDbType.DateTime));
seCmd.Parameters.Add(new SqlParameter("@CurrentStage", SqlDbType.NVarChar,500));
seCmd.Parameters.Add(new SqlParameter("@OtherRef", SqlDbType.NVarChar, 500));
seCmd.Parameters["@ServiceID"].Value = strServiceID;
seCmd.Parameters["@SupplierOrderNumber"].Value = strSupplierOrderNo;
seCmd.Parameters["@Comments"].Value = strComment ;
seCmd.Parameters["@OrderDate"].Value = strOrderDate;
seCmd.Parameters["@RequiredLiveDate"].Value = strRequiredLive;
seCmd.Parameters["@AppointmentDate"].Value = strActualAppointmentDate;
seCmd.Parameters["@ReviewDate"].Value = strReviewDate;
seCmd.Parameters["@CurrentStage"].Value = strCurrentStage;
seCmd.Parameters["@OtherRef"].Value = strOtherRef;
SqlDataAdapter dbAdapter = new SqlDataAdapter(seCmd);
DataSet dbSeDataset = new DataSet();
dbAdapter.Fill(dbSeDataset);
seConnection.Close();
}
just for completion i have put an error from firebug when i try to add an apostrophe in the middle of a wrod: 只是为了完成,当我尝试在粗体中间添加撇号时,我已经从萤火虫发出了错误:
"Invalid object passed in, ':' or '}' expected. (50): {'args': '158581,aaa5-5-23264304431 ,aaaaaCustom'er%20still%20not%20ready%20as%20civils%20work%20has%20still%20not%20been%20completed%20%26%20currently%20there%20still%20hasn%27t%20been%20any%20duct/cable/dp%20installed%2C%20as%20confirmed%20with%20the%20site%20contact%20Steve%20Williams%20who%20was%20unaware%20of%20this%20appointment.%20Also%20this%20quoted%20dp%20will%20be%20the%20incorrect%20dp%20as%20the%20address%20for%20the%20dp%20is%20an%20ext%u2019l%20block%20at%2015%20Seel%20street%20%26%20the%20premier%20inn%20is%20a%20brand%20new%20hotel%20just%20being%20completed.%0A%20Also%20rang%20the%20project%20team%20to%20inform%20them%20of%20the%20reasons%20for%20the%20delay.%0A%0ASMCYB07%2027/09/2012%2014%3A50%3A00%0A,Civils,22/05/2013,22/05/2013,22/05/2013,22/05/2013,aaaa'}" StackTrace " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) at System.Web.Script.Serialization.JavaScript “传入了无效的对象,预期为':'或'}'。(50):{'args':'158581,aaa5-5-23264304431,aaaaaCustom'er%20still%20not%20ready%20as%20civils%20work%20has %20still%20not%20been%20完成%20%26%20当前%20there%20still%20hasn%27t%20been%20any%20duct / cable / dp%20 Installed%2C%20as%20confirmed%20with%20the%20site%20contact%20Steve %20Williams%20who%20w %% 20of%20this%20pointing。%20Also%20this%20quoted%20dp%20will%20be%20the%20incorrect%20dp%20as%20the%20address%20for%20the%20dp%20is%20an% 20ext%u2019l%20block%20at%2015%20Seel%20street%20%26%20the%20premier%20inn%20is%20a%20brand%20new%20hotel%20just%20being%20complete。%0A%20Also%20rang%20the%20project %20team%20to%20inform%20them%20of%20the%20reasons%20for%20the%20delay。%0A%0ASMCYB07%2027/09/2012%2014%3A50%3A00%0A,Civils,22/05 / 2013,22 / 05 / 2013,22 / 05 / 2013,22 / 05/2013,aaaa'}“ StackTrace”在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32深度)在System.Web.Script.Serialization.JavaScript ObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)" ExceptionType "System.ArgumentException" System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input,Int32 depthLimit,JavaScriptSerializer serializer)处的ObjectDeserializer.DeserializeInternal(Int32 depth)(System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer,String input,Type type) ,在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)在System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext上下文,JavaScriptSerializer序列化器)在System.Web.Script.Services System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext上下文,WebServiceMethodData methodData)处的.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext上下文)“ ExceptionType” System.ArgumentException“
使用System.Net.WebUtility.HtmlDecode()解码注释。
seCmd.Parameters["@Comments"].Value = System.Net.WebUtility.HtmlDecode(strComment);
You can use encodeURI( http://www.w3schools.com/jsref/jsref_encodeuri.asp ) or encodeURIComponent( http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp ) on client side and Url.Unescape( http://msdn.microsoft.com/en-us/library/system.uri.unescape.aspx ) on server side. 您可以使用是encodeURI( http://www.w3schools.com/jsref/jsref_encodeuri.asp )或encodeURIComponent方法( http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp在客户端和Url.Unescape() HTTP: //服务器端的//msdn.microsoft.com/zh-CN/library/system.uri.unescape.aspx )。
and instead of data: "{'args': '" + EditRecordArgs + "'}"
as my mind better to use 而不是data: "{'args': '" + EditRecordArgs + "'}"
data: "{'arg1': '" + arg1Value + "', arg2': '"+ arg2Value ...+" }"
for avoid problems with Trim
为了避免Trim
问题
I will suggest instead of passing values comma seperated use json objects. 我建议不要使用逗号分隔使用json对象来传递值。 It will be more clear and you can pass values easily. 它将更加清晰,您可以轻松传递值。
Make a JS class 制作一个JS类
EditRecordArgs = {};
EditRecordArgs.ServiceID = '“' + strServiceID+ '”';
EditRecordArgs.SupplierNo = '“' + strSupplierOrderNo + '”';
EditRecordArgs.Comment = '“' + strComment + '”';
. 。
.. ..
.... ....
Make a class in C# 用C#上课
Public ServiceRecord
{
public string ServiceID{get; set;}
public string SupplierNo{get; set;}
public string Comment{get; set;}
}
In a class 上课
use namespace 使用名称空间
using System.Web.Script.Serialization;
In a web Method 网络方式
ServiceRecord r = ser.Deserialize<ServiceRecord>(args);
Hope this will help you. 希望这会帮助你。
Use JSON string to send data to server and deserialize data back from server. 使用JSON字符串将数据发送到服务器,并从服务器反序列化数据。
$("#btnEditFields").click(function () {
//Store the New comment
var data = {};
data.strSupplierOrderNo =$("#<%=tbPopUpEditSuppOrdNo.ClientID%>").val();
data.strComment =$("#<%=tbPopUpEditComments.ClientID%>").val();;
.
.
.
...
// Confirming the operation from the user
if (confirm("You are about to add a new comment to order " + strPSTNNum + "?")) {
$.ajax({
type: "POST",
//UpdateRecordInGridViewUsingAjax.aspx is the page name and UpdateOrder
// is the server side web method which actually does the updation
url: "PSTN_OrderManagementTracker.aspx/updatePSTNDataInDB",
//Passing the record id and data to be updated which is in the variable update_data
data: {args: JSON.stringify(data)},
contentType: "application/json; charset=utf-8",
dataType: "json",
//Giving message to user on successful updation
success: function () {
alert("Comment successfully added!!!");
location.reload();
},
error: function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
}
return false;
});
});
And the Code behind 和背后的代码
[System.Web.Services.WebMethod]
public static void updatePSTNDataInDB(string args)
{
var serializer = new JavaScriptSerializer();
Dictionary<string, string> jsonObjects = serializer.Deserialize<Dictionary<string, string>>(args);
strSupplierOrderNo = jsonObjects[strSupplierOrderNo];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.