最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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/

发布评论

评论列表(0)

  1. 暂无评论