简体   繁体   中英

asp.net webforms - how to get the json data of a javascript function using c#

I have a function in my javascript that returns a json . I want to get the return value of that javascript function using c# so I can convert it in dataTable. Can anyone help me? Sorry I'm just a beginner in asp.net webforms.

JS

function getAllMessages()
    {
        $.ajax({
            url: '/api/Messages/',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'JSON'
        }).success(function (result) {

        });
    }

since you don't have the actual code , i'll just give an algorithm. I experienced this scenario in one of my projects.

In your html/asp.net button, execute a webmethod that has a parameter to receive the json format

 $.ajax({
            type: 'POST',
            url: 'YourPage.aspx/c#MethodThatWillReceiveJSON',
            data: "{c#MethodParameterName:" + JSON.stringify(YourJSONvalues) + "}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (r) {
                alert(r.d.exampleDataFromJson);

            }
        });

You need to create another javascript function that will call your original javascript (The one who will return the json format) and use that function to pass it as an argument to the parameter of your c# webmethod.

//your original javascript function that returns json
  function getJsonData()
  {
   // your code
  }

  // use that js function to store in a var , then pass it to your c#
   var MyJSONdata = getJSONData();
   $.ajax({
        type: 'POST',
        url: 'YourPage.aspx/c#MethodThatWillReceiveJSON',
        data: "{c#MethodParameterName:" + JSON.stringify(MyJSONdata) + "}",
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (r) {
            alert(r.d.exampleDataFromJson);

        }
    });

If you use a String type as a parameter in your c# webmethod, you can not use/manipulate it as a json stuff, you need to convert your String variable using json serializer :) which you can find a lot of reference here in net/stackoverflow, it is just one liner of code to convert. :)

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