0

我有一个 ajax 调用从 aspx 页面向 webmethod (c#) 发送一些数据,发送的参数之一是一些自由文本评论。现在我注意到了一些错误,并且没有对数据库进行更新。因此,通过一些检查,我相信它的斜线和 's 以及可能导致这种情况的其他字符。我尝试使用 escape() 方法并且它有效,但随后将各种编码文本添加到我不想要的数据库中。我不是一个经验丰富的编码员,所以我知道这里有某种编码要做,但我不确定。这是下面的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;
});
});

这是网络方法:

[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();
}

只是为了完成,当我尝试在 wrod 中间添加撇号时,我从 firebug 中输入了一个错误:

“传入的对象无效,应为':'或'}'。(50):{'args':'158581,aaa5-5-23264304431,aaaaaCustom'er%20still%20not%20ready%20as%20civils%20work%20has %20 仍然 %20 未 %20 已 %20 已完成 %20%26%20 当前%20 存在 %20 仍%20 已 %27t%20 已%20 任何%20 管道/电缆/dp%20 已安装%2C%20as%20 已确认%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”在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 深度)在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 深度)在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入,Int32 depthLimit,JavaScriptSerializer 序列化程序)在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer 序列化程序,字符串输入,类型类型,Int32 depthLimit)在系统。 Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](字符串输入)在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext 上下文,JavaScriptSerializer 序列化程序)在 System.Web.Script.Services.RestHandler。GetRawParams(WebServiceMethodData methodData,HttpContext context)在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)”异常类型“System.ArgumentException”

4

4 回答 4

0

使用 System.Net.WebUtility.HtmlDecode() 解码评论。

seCmd.Parameters["@Comments"].Value = System.Net.WebUtility.HtmlDecode(strComment);
于 2013-05-22T16:53:09.260 回答
0

您可以在客户端和Url.Unescape ( http : //msdn.microsoft.com/en-us/library/system.uri.unescape.aspx)在服务器端。

而不是data: "{'args': '" + EditRecordArgs + "'}"我的想法更好地使用

data: "{'arg1': '" + arg1Value + "', arg2': '"+ arg2Value ...+" }"

为了避免出现问题Trim

于 2013-05-22T16:59:57.010 回答
0

我会建议使用 json 对象而不是使用逗号分隔的值传递值。它会更清晰,您可以轻松传递值。

做一个 JS 类

EditRecordArgs = {};
EditRecordArgs.ServiceID = '“' + strServiceID+ '”'; 
EditRecordArgs.SupplierNo = '“' + strSupplierOrderNo + '”'; 
EditRecordArgs.Comment = '“' + strComment + '”'; 

.

..

……

在 C# 中创建一个类

Public ServiceRecord
{
public string  ServiceID{get; set;}
public string  SupplierNo{get; set;}
public string  Comment{get; set;}
}

在一个班级

使用命名空间

using System.Web.Script.Serialization;

在网络方法中

ServiceRecord r = ser.Deserialize<ServiceRecord>(args); 

希望这会帮助你。

于 2013-06-02T03:14:57.207 回答
0

使用 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;
    });
    });

以及背后的代码

[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];
}
于 2013-06-04T06:17:05.890 回答