How to pass json string to webmethod c# ASP.NET
Asked Answered
A

2

7

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 500 and the stacktrace says that value is missing for parameter.

Here is the javascript code:

var jSon = JSON.stringify(javascriptObject); 
// "{"Foretagsnamn":"Avector","BGFarg":"000000","TextColor":"fafafa","FooterFarg":"ffffff","FooterColor":"000000","FooterLinkColor":"050505","FeaturedBorderColor":"","HoverFarg":"12ebeb","RutFarg":"0d0d0d","SelectedRutFarg":"","RutColor":"FFFFFF","LankColor":"","DelaMedSig":"1","PersonalSida":"0","StartpageTitle":"","StartpageDescription":"","GoogleMaps":"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.se/maps?f=q&amp;source=embed&amp;hl=sv&amp;geocode=&amp;q=Avector AB&amp;aq=&amp;sll=56.225986,12.870827&amp;sspn=0.076248,0.154324&amp;ie=UTF8&amp;hq=Avector AB&amp;hnear=&amp;t=m&amp;cid=645910733081021950&amp;iwloc=A&amp;ll=56.224594,12.859229&amp;spn=0,0&amp;output=embed\"></iframe><br /><small><a href=\"https://maps.google.se/maps?f=q&amp;source=embed&amp;hl=sv&amp;geocode=&amp;q=Avector AB&amp;aq=&amp;sll=56.225986,12.870827&amp;sspn=0.076248,0.154324&amp;ie=UTF8&amp;hq=Avector AB&amp;hnear=&amp;t=m&amp;cid=645910733081021950&amp;iwloc=A&amp;ll=56.224594,12.859229&amp;spn=0,0\" style=\"text-align:left\">Visa större karta</a></small>","HittaKartaUrl":"http://www.hitta.se/avector ab/ängelholm/hxTP-4v1HG?vad=Avector AB","EniroKartaUrl":"http://kartor.eniro.se/m/aKkhi","Ikoner":"2","Email":"[email protected]","AdressSida":"1","shadowColor":"ffffff","lineColor":"2b292b","MenuHoverIcon":"Välj bild från server","fontFamily":"Verdana","supportText":"Support Avector","captcha":true,"metaKeywords":"","ShowSupportInFooter":true}"

$.ajax({
    type: "POST",
    url: "Post/Installningar.aspx/Updatera",
    data: jSon,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {

        var resultAsString = result.d;
        //_this.parent().siblings('.SavedStatus').html(resultAsString);

        if (resultAsString == "1") { // Gick bra att spara.
           alert("Uppgifterna är sparade.");
           document.location = document.location;
        }
        else {
           $('#StatusText').html("Gick inte att spara uppgifterna.");
        }


    },
    error: function (xhr, ajaxOptions, thrownError) {

    }
});

And here Is the webmethod:

[WebMethod]
public static string Updatera(string jSon)
{

It feels like I've tried everything that I've found when searching by google and here on SO.

I've also tried this guide that many refer to: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Any ideas?

Arlyne answered 23/4, 2015 at 8:28 Comment(5)
Depending on the content of javascriptObject, you may need to serialise it differently. Try setting traditional: true and data: javascriptObject in the $.ajax call instead.Allopatric
try replacing data: jSon, with data: {"jSon":JSon},Ordinand
@jonamreddy Ive changed data: jSon to data: { "jSon": jSon }, I still get error, now saying "Invalid json primitive".Arlyne
Can you share jSon value?Ordinand
@jonamreddy I've updated the OP with the jSon value.Arlyne
S
11

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
}
Stare answered 23/4, 2015 at 16:33 Comment(1)
I know its a old one but, it will be useful to someone like me We generally use string as a paramater type as below [WebMethod] public static string Updatera(**string** obj) { // logic code } But we have to use parameter as class type, in the above case JSON type is of type aData class [WebMethod]<br/> public static string Updatera(**aData** obj) { // logic code } Exorable
S
0

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

Spartacus answered 23/4, 2015 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.