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

后端 未结 2 1918
盖世英雄少女心
盖世英雄少女心 2020-12-20 19:11

Im trying to stringify a javascript object and then pass the string as a parameter to a WebMethod in Code Behind. I can\'t get it to work as I get a Internal Server Error of

2条回答
  •  醉梦人生
    2020-12-20 19:37

    First, you need to use:

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

    instead of:

    var jSon = JSON.stringify(javascriptObject);
    

    Then your 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){
        // Do something
    }
    function OnErrorCall(){
        // Do something
    }
    

    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

提交回复
热议问题