【问题标题】:Why doesn't the action method accept a parameters from the ajax call?为什么 action 方法不接受来自 ajax 调用的参数?
【发布时间】:2021-04-29 04:04:04
【问题描述】:

我正在将 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
            {

我尝试了一切,但它是空的。请帮我解决这个问题。

【问题讨论】:

    标签: c# ajax asp.net-mvc model-view-controller


    【解决方案1】:

    这段代码:

                   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= "")
    

    【讨论】:

      【解决方案2】:

      我举个简单的例子,试着把你的代码和它匹配起来

      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>

      【讨论】:

      • 嗨 meysam,谢谢。这很有帮助,但由于我对此很陌生,所以我实际上无法找出我的代码的问题。
      • 请帮我看看代码的问题是什么
      • 您希望何时将信息发送给控制器?我举了一个使用自动完成的例子
      猜你喜欢
      • 2012-01-14
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多