将数据从javaScript传递到MVC控制器视图ajax

passing data from javaScript to MVC controller view ajax

本文关键字:MVC 控制器 视图 ajax 数据 javaScript      更新时间:2023-09-26

这很奇怪,我不知道为什么这不起作用,无论我做什么,我总是收到操作方法参数的null。为什么不起作用?

<input type="button" value="Save" onclick="SaveDocument()"  />

       function SaveDocument() {
            
         var data = "sss";
            $.ajax({
                url: "/Home/Save",
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(data),
                success: function (mydata) {
                    alert("Saved");
                },
                error: function(error)
                {
                    alert('failed');
                    alert(error);
                }
            });
          
        }
    
    </script>

    [HttpPost]
    public ActionResult Save(string data)
    {
        return null;
    }

我在本地创建了相同的测试代码。我和你一样空。您可以使用以下代码进行尝试。它对我有效。

function SaveDocument() {          
        $.ajax({
            url: "/Home/Save",
            type: "POST",               
            data: {"data" : "sss"},
            success: function (mydata) {
                alert("Saved");
            },
            error: function(error)
            {
                alert('failed');
                alert(error);
            }
        });
    }

您应该将一个js对象(键值对(传递给JSON.stringify方法,以便通过ajax调用发送字符串化版本的数据。键/对象属性名称应与操作方法参数名称匹配。

以下内容应该有效。

data: JSON.stringify({ data:"some string"}),
contentType: "application/json; charset=utf-8",

您可能还想在js方法中考虑return false;,这样就不会发生正常的表单提交。

此外,由于服务器操作方法返回null,因此不应将"json"指定为ajax调用的"dataType"属性值。只需从ajax调用中删除该行即可。

或者您可以从操作方法返回一些有效的json数据,而不是null

[HttpPost]
public ActionResult Save(string data)
{
  return Json(data);
}

将动作参数名称更改为其他有意义的名称。data是jQuery中的一个保留关键字。

[HttpPost]
public ActionResult Save(string tempName)
{
  return Json(tempName);
}
//Javascript method
function postData(parsData)
    {
       var dataToSend = {  ParsData: parsData};
       var ReceivedData= JSON.stringify( dataToSend );
       $.ajax({
                 url: '@Url.Action("SetData")',
                 type: 'POST',
                 data: ReceivedData
       }).done(function (response) 
       {
           console.log(response);
           document.getElementById("result").innerHTML = response.resultHint;
           document.getElementById("amount").innerHTML = response.resultAmount;
           document.getElementById("image").src = response.imageUrl;
        });
    }
//Javascript method Implementation
postData("Fuking code");
//C# Controller
public class ReceivedData
        {
            public string ParsData{ get; set; }
        }
        public class Result
        {
            public string resultHint { get; set; }
            public string resultAmount { get; set; }
            public string imageUrl { get; set; }
            public string decoded { get; set; }
        }
        [HttpPost]
        public ActionResult SetData()
        {
            //var jss = new JavaScriptSerializer();
           // ReceivedData decodedQR = new JavaScriptSerializer().Deserialize<ReceivedData>(receivedData);
            // var dataObject = new JavaScriptSerializer().Deserialize(receivedData);
            // .. do something with data object 
            var jsonFromRequest = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
            ReceivedData decodedQR = Newtonsoft.Json.JsonConvert.DeserializeObject<ReceivedData>(jsonFromRequest);

            Result result= new Result();
            result.resultHint = "Tem certeza que pretende permitir que o João Deposite o valor de ";
            result.decoded = decodedQR.ParsData;
            result.resultAmount = "200 MT";
            result.imageUrl = "https://picsum.photos/id/237/200/300";
            return Json(result);
        }

Credit to:https://mestanzasoft.wordpress.com/2018/03/05/pass-data-from-asp-net-mvc-view-to-controller-with-ajax-and-json/