How to pass json string to webmethod c# ASP.NET

末鹿安然 提交于 2019-11-29 14:13:42

First you need to use

var jSon = JSON.stringify({obj:javascriptObject});

instead of

var jSon = JSON.stringify(javascriptObject);

Then you webmethod would be like

[WebMethod]
public static string Updatera(aData obj)
{
  // logic code 
}

Now here aData is your class something like below

public class aData { 
        public string Foretagsnamn  {get;set;}
         public string BGFarg  {get;set;}
         public string TextColor  {get;set;}
         public string FooterFarg  {get;set;}
         public string Email  {get;set;}
       }

So your final code look like

jQuery :

 var jSon = JSON.stringify({obj:javascriptObject});
            $.ajax({
                type: "POST",
                url: "Post/Installningar.aspx/Updatera",
                data: jsonData,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnErrorCall
            });

            function OnSuccess(response){

            }

            function OnErrorCall(){

            }

Code Behind :

 public class aData { 
    public string Foretagsnamn  {get;set;}
    public string BGFarg  {get;set;}
    public string TextColor  {get;set;}
    public string FooterFarg  {get;set;}
    public string Email  {get;set;}
}


[WebMethod]
public static string Updatera(aData obj)
{
   // logic code 
}

Do check jQuery Ajax JSON Example in Asp.net

Use this format for ajax post format :

var jSon = JSON.stringify(javascriptObject);

Your Json Format will be like this : '{name: "' + name +'" }',

function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "Installningar.aspx/Updatera",
        data: jSon; 
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
}
function OnSuccess(response) {
    alert(response.d);
}

Follow this step for complete run your code : http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!