简体   繁体   中英

passing data from javaScript to MVC controller view ajax

This is strange, I have no clue why this is not working, no matter what I do, I am always end up receiving null for the action method parameter. Why is that not working?

<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;
    }

I have created same test code in my local. i get null as you get. You can try with below code. it worked for me.

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

You should pass a js object(key value pair) to the JSON.stringify method, for sending the stringified version of data via your ajax call. The key/object property name should match with your action method parameter name.

The below should work.

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

You might also want to consider a return false; in your js method so that the normal form submission won't happen.

Also since your server action method is returning null , you should not specify "json" as the " dataType " property value for your ajax call. Just remove that line from your ajax call.

Or you can return some valid json data from your action method instead of null

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

Change the action parameter name to some other meaningful name. data is a reserved keyword in 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM