asp.net mvc - passing data from javaScript to MVC controller view ajax - Stack Overflow

This is strange, I have no clue why this is not working, no matter what I do, I am always end up receiv

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>

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;
    }
Share Improve this question edited Oct 11, 2016 at 21:29 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Oct 11, 2016 at 21:02 lucaslucas 4,6856 gold badges31 silver badges52 bronze badges 2
  • JSON.stringify("sss") resolves to ""sss"" So this might be a problem, because this is not a valid JSON. – Canilho Commented Oct 11, 2016 at 21:24
  • 1 Look at @Jaimin Dave solution ... in your ajax call you have to pass { "data": "some string" } – Piotr Pasieka Commented Oct 12, 2016 at 5:34
Add a ment  | 

4 Answers 4

Reset to default 4

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./2018/03/05/pass-data-from-asp-net-mvc-view-to-controller-with-ajax-and-json/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744730923a4590462.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信