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

问题描述

我正在将 FileHeadNo 从 ajax 发送到我的控制器操作,但它没有收到 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>

控制器类

[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 帮助类

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 类

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] 添加到您的操作标题:

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