为什么 action 方法不接受来自 ajax 调用的参数?

Why doesn't the action method accept a parameters from the ajax call?

我正在从 ajax 向我的控制器操作发送 FileHeadNo,但它没有收到 FileHeadNo。

 $(function () {
        $("#txtReportNo").autocomplete({
            source: function (request, response) {

                var reportNo = $("#txtReportNo").val();
                var FileHeadNo = $("#txtFileHeadNo").val();
                var InitialsID = ""; //$("#CNGInspectionReport_InitialsID").val();
                var ProjectID = ""; //$("#CNGInspectionReport_ProjectID").val();
                var url;
                var data;
                var onlyReport = 0;
                // console.log(InitialsID + " " + ProjectID);

                //if (($("#CNGInspectionReport_InitialsID").val() == null || $("#CNGInspectionReport_InitialsID").val() == "" || $("#CNGInspectionReport_InitialsID").val() == "0") && ($("#CNGInspectionReport_ProjectID").val() == "" || $("#CNGInspectionReport_ProjectID").val() == "0")) {

                url = "/CNGInspectionReport/GetInspectionReportFilteredIssuedOnly"
                reportNo = { reportNo: $("#txtReportNo").val() };
                data = JSON.stringify(reportNo);
                onlyReport = 1;

                if (onlyReport == 1) {
                    data = JSON.stringify(reportNo);
                }
                else {
                    var Listdata = { reportNo: $("#txtReportNo").val(), FileHeadNo: $("#txtFileHeadNo").val() };       
                    data = JSON.stringify(Listdata); 
                }

                $.ajax({
                    url: url,
                    data: data,
                    dataType: "json",
                    type: "POST",
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        //debugger;
                        //response(JSON.parse(data));
                        response($.map(data.result, function (item) {
                            return {
                                value: item   //item.VelosiReportNo
                            }
                        }))
                    },
                    //error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    //    alert(err.Message)
                    //}
                });
            },
            minLength: 1 //This is the Char length of inputTextBox
        });
    });

这是操作方法,但它收到的 FileHeadNo 为空。

public ActionResult GetInspectionReportFilteredIssuedOnly(string reportNo, string FileHeadNo= "")
        {
            try
            {

我什么都试过了,但它是空的。请帮我解决这个问题。

我会举一个简单的例子,试着匹配你的代码

ajax请求:

<script>
      $('.addtobasket').click(function () {
           var productid = $(this).attr('productid');
           var count = $(this).attr('count');
           $.ajax({
              url: "/Basket/AddToBasket",
              data: { productid : productid , count : count },
              type: "Post",
              dataType: "Json",
              success: function (result) {
                 if(result.Success)
                 {
                    $("#framebasket").html(result.HtmlBody);
                 }
                 else
                 {
                    alert(result.HtmlMsg);
                 }
               },
               error: function () {
                    alert("error");
               }
          });
      });
    </script>

控制器class

[HttpPost]
public ActionResult AddToBasket(int productid, int count)
{
    //add to basket......
    return Json(new JsonData()
    {
        HtmlMsg = "Item Add to Your Basket",
        HtmlBody = this.RenderPartialToString("_BasketList", model),
        Success = true,
    });
}

html帮手class

public static class ViewHelper
{
    public static string RenderPartialToString(this ControllerBase controller, string partialViewName, object model)
    {
        IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
        return RenderViewToString(controller, view, model);
    }
}

现在 JsonData Class

public class JsonData
{
    public string HtmlMsg { get; set; }
    public string HtmlBody { get; set; }
    public bool Success { get; set; }
}

希望有用

查看此代码:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>autocomplete demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
 
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">
 
<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
$( "#autocomplete" ).autocomplete({
  source: function( request, response ) {
          var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
          response( $.grep( tags, function( item ){
              return matcher.test( item );
          }) );
      }
});
</script>
 
</body>
</html>

此代码:

               url = "/CNGInspectionReport/GetInspectionReportFilteredIssuedOnly"
                reportNo = { reportNo: $("#txtReportNo").val() };
                data = JSON.stringify(reportNo);
                onlyReport = 1;

                if (onlyReport == 1) {
                    data = JSON.stringify(reportNo);
                }
                else {
                    var Listdata = { reportNo: $("#txtReportNo").val(), FileHeadNo: $("#txtFileHeadNo").val() };       
                    data = JSON.stringify(Listdata); 
                }

替换为:


url = "/CNGInspectionReport/GetInspectionReportFilteredIssuedOnly"

var data;

 if (onlyReport == 1) {
   data = {reportNo:reportNo, FileHeadNo:""};
  }
  else {
  data = {reportNo:reportNo, FileHeadNo:FileHeadNo};
 }

从 ajax 中删除此代码:

dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },

并将 [FromBody] 添加到您的操作中 header:

public ActionResult GetInspectionReportFilteredIssuedOnly([FromBody] string reportNo, string FileHeadNo= "")