javascript - 如何在c# asp.net中保存特殊字符

标签 javascript c# asp.net-mvc-3

我有这个JS下面的代码用于保存用户输入的数据。所有数据可见var JsonData = JSON.stringify(data); 。我在Task (& sign)中输入了一个特殊字符[Task Value is (A & B)] 。但在我的 Controller 中它在 & 之前剪切了数据标志。

$('#btn_SubmitOT').live('click', function () {
    if (lastSel != -1) {
        $('#' + lastSel + '_isValidated').val(true);
        //            $('#' + lastSel + '_RequestedBy').val();
        var datefiled = $('#ot_dateFiled').val().
        $('#' + lastSel + '_OTDateApplied').val(datefiled);
        jQuery('#grdOTApplication').saveRow(lastSel, false, 'clientArray');
    }
    var task = $("#task_ot").val();
    //var data = $("#grdOTApplication").jqGrid('getRowData');
    var data = {
        DateFiled: $("#ot_dateFiled").val(),
        DateofOvertime: $("#ot_dateOfOT").val(),
        EmployeeId: $("#empApplicants").val(),
        In1: $("#from_sup").val() + $("#from_AM_PM").val(),
        Out1: $("#to_sup").val() + $("#to_AM_PM").val(),
        EstimatedHours: $("#estimateHrsWrk_ot").val(),
        SpecificTask: task,
        ApprovedBy: $("#approveofficial").val() != null ? $("#approveofficial").val() : 0,
        RecommendedBy: $("#recommenders").val() != null ? $("#recommenders").val() : 0,
        SupervisedBy: $("#immediatesupervisor").val() != null ? $("#immediatesupervisor").val() : 0,
        IsCOC: $('#cmbCO').val() == 1 ? true : false
    }


    var JsonData = JSON.stringify(data);

    var urlPA = '../Request/saveOvertimeRequest?overtimeRequest=' + JsonData + '&_role = 3;

    $.ajax({
        type: "GET",
        url: urlPA,
        success: function (response) {
            alert(response);
            $("#grdOTApplication").trigger("reloadGrid", [{
                current: true
            }]);
            $("#grdOTHistory").trigger("reloadGrid", [{
                current: true
            }]);
            $("#ot_dateOfOT").val("");
            $("#from_sup").val("__:__");
            $("#to_sup").val("__:__");
            $("#estimateHrsWrk_ot").val("");
            $("#task_ot").val("");
        },
        error: function (response) {
            alert("Error");
        },
        datatype: "text"
    });
});

这是我的 Controller 代码,我放置了一个断点并调试它,为什么在它到达此代码ovt = jss.Deserialize<OvertimeRequest>((string)overtimeRequest);之后它直接到catch 。正如我上面提到的,它会在 & 之前剪切数据。标志。

public String saveOvertimeRequest(String overtimeRequest, int _role)
    {
        Nullable<DateTime> MyNullableDate = null;
        try
        {
            Int32 requestedBy = Convert.ToInt32(HttpContext.Current.Session["PersonId"]);
            Int32 empId = Convert.ToInt32(HttpContext.Current.Session["EmpId"]);

            OvertimeRequest ovt = new OvertimeRequest();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ovt = jss.Deserialize<OvertimeRequest>((string)overtimeRequest);
            ovt.IsFromESS = true;
            ovt.RequestedBy = requestedBy;
            if (_role == 3 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && ovt.RecommendedBy > 0 && ovt.ApprovedBy > 0))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;

            }
            if (_role == 4 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && (ovt.RecommendedBy == 0 || ovt.RecommendedBy == null) && ovt.ApprovedBy > 0))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;
                ovt.RecommendedBy = null;
                ovt.DateRecommend = DateTime.Now;

            }
            if (_role == 5 || ((ovt.SupervisedBy == 0 || ovt.SupervisedBy == null) && (ovt.RecommendedBy == 0 || ovt.RecommendedBy == null) && (ovt.ApprovedBy == 0 || ovt.ApprovedBy == null)))
            {
                ovt.SupervisedBy = null;
                ovt.DateSupervised = DateTime.Now;
                ovt.RecommendedBy = null;
                ovt.DateRecommend = DateTime.Now;
                ovt.ApprovedBy = null;
                ovt.DateApproved = DateTime.Now;
                ovt.IsPosted = true;
                ovt.DatePosted = DateTime.Now;
            }
            try
            {
                db.AddToOvertimeRequests(ovt);
                db.SaveChanges();
            }
            catch (Exception)
            {
                throw;
            }
          }
        catch (Exception e)
        {
            return "An error has occured while sending your request.";
        }
    }

JS

Control

最佳答案

由于您正在执行 GET 请求,因此您正在丢失数据。当您执行 GET 调用时,数据将作为查询字符串发送,并且 & 在查询字符串中具有特殊含义。它是不同查询字符串项的分隔符。

您应该做的是对服务器进行 POST 调用。此外,无需显式进行反序列化,因为模型绑定(bind)程序会为您完成此操作。只需创建一个 C# POCO 类来表示您要发送的数据结构,并将其用作操作方法参数。

public class OverTimeViewModel
{
  public DateTime DateFiled { set;get;}
  public DateTime DateofOvertime { set;get;}
  public int EstimatedHours { set;get;}
  //Add other properties here
}

并在 javascript 代码中,使用 POST 作为 ajax 方法。

var viewModel = {
                  DateFiled: '12/12/2012'
                  EstimatedHours : 10
                } ;
// values hard coded for demo. Replace with real values
$.ajax({
    type: "POST",
    url: urlPA,
    data : viewModel 
    success: function (response) {
      //do something with the response
    }
});

现在请确保使用我们创建的 View 模型作为参数

public ActionResult SaveOvertimeRequest(OverTimeViewModel model)
{
  //check model.DateField etc and use 
}

关于javascript - 如何在c# asp.net中保存特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651147/

相关文章:

javascript - jQuery - 监听用户点击浏览器提供的自动建议选项

c# - 如何在 C# 中将字符串值转换为 HTMLAnchor

css - MVC 3、CSS、Razor 和 Visual Studio 2010

jquery - 在 MVC 3 中,使用 jQuery Validator 无法正确验证小数

javascript - MVC3,同一个页面View之间的切换

javascript - .off 不适用于回调

javascript - 是否可以保护 cookie?

javascript - 关于 d3.interpolate 对象的困惑

c# - 删除具有特定名称和动态文件扩展名的文件

c# - WCF 服务引用 - 在客户端获取 "XmlException: Name cannot begin with the ' <' character, hexadecimal value 0x3C"