javascript 如何将 json 字符串传递给 webmethod c# ASP.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29817796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:07:20  来源:igfitidea点击:

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

javascriptjqueryasp.netajaxwebmethod

提问by Paul Chefen Lagmark

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.

我试图对一个 javascript 对象进行字符串化,然后将该字符串作为参数传递给代码隐藏中的 WebMethod。我无法让它工作,因为我收到 500 的内部服务器错误,并且堆栈跟踪显示参数值丢失。

Here is the javascript code:

这是javascript代码:

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/

我也试过很多人参考的这个指南:http: //encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

Any ideas?

有任何想法吗?

回答by Satinder singh

First you need to use

首先你需要使用

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

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

instead of

代替

var jSon = JSON.stringify(javascriptObject);

var jSon = JSON.stringify(javascriptObject);

Then you webmethod would be like

那么你的 webmethod 会像

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

Now here aData is your class something like below

现在这里 aData 是你的类,如下所示

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 :

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

在 Asp.net 中检查jQuery Ajax JSON 示例

回答by Mayank Patel

Use this format for ajax post format :

将这种格式用于 ajax 帖子格式:

var jSon = JSON.stringify(javascriptObject);

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

你的 Json 格式将是这样的:'{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

按照此步骤完整运行您的代码:http: //www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx