title: string sent to a webmethod with json/ajax
body: <p>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 </p>
  
  <pre><code>$("#btnEditFields").click(function () {
      //Store the New comment
      var strSupplierOrderNo = $("#&lt;%=tbPopUpEditSuppOrdNo.ClientID%&gt;").val();
      var strComment = $("#&lt;%=tbPopUpEditComments.ClientID%&gt;").val();
      var strCurrentStage = $("#&lt;%=ddlPopUpEditCurrentStage.ClientID%&gt;").val();
      var strReviewDate = $("#&lt;%=tbPopUpEditReviewDate.ClientID%&gt;").val();
      var strOrderDate = $("#&lt;%=tbPopUpEditOrderDate.ClientID%&gt;").val();
      var strRequiredLive = $("#&lt;%=tbPopUpEditRequiredLiveDate.ClientID%&gt;").val();
      var strActualAppointmentDate = $("#&lt;%=tbPopUpEditActualAppointmentDate.ClientID%&gt;").val();
      var strOtherRef = $("#&lt;%=tbPopUpFieldOtherRef.ClientID%&gt;").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;
  });
  });
  </code></pre>
  
  <p>Here Is the web method:</p>
  
  <pre><code>[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();
  }
  </code></pre>
  
  <p>just for completion i have put an error from firebug when i try to add an apostrophe in the middle of a wrod:</p>
  
  <blockquote>
    <p>"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.JavaScriptObjectDeserializer.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"</p>
  </blockquote>