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. 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. 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
$("#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 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.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.
and instead of data: "{'args': '" + EditRecordArgs + "'}"
as my mind better to use
data: "{'arg1': '" + arg1Value + "', arg2': '"+ arg2Value ...+" }"
for avoid problems with Trim
I will suggest instead of passing values comma seperated use json objects. It will be more clear and you can pass values easily.
Make a JS class
EditRecordArgs = {};
EditRecordArgs.ServiceID = '“' + strServiceID+ '”';
EditRecordArgs.SupplierNo = '“' + strSupplierOrderNo + '”';
EditRecordArgs.Comment = '“' + strComment + '”';
.
..
....
Make a class in 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.
$("#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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.