繁体   English   中英

如何将jquery中的string []类型参数传递给asp.net Web API方法?

[英]How to pass string[] type parameters from jquery to asp.net web api method?

我想从jquery调用中将3个参数传递给Web api方法:

字符串[] a,字符串[] b,字符串[] c。 但是我不能 。

    <script type="text/javascript">

    function fncsave() {

        var arrtemplate = [];
        var arrrole = [];
        var arrpcode = [];
        $('#mytemplateTags li').each(function () {
            var str = $(this).html();
            var res = str.match("<span class=\"tagit-label\">(.*?)</span>");
            if (res!=null) {
                var str = res[1];

                arrtemplate.push(str);
            }
        });

        $('#myroleTags li').each(function () {
            var str = $(this).html();
            var res = str.match("<span class=\"tagit-label\">(.*?)</span>");
            if (res != null) {
                var str = res[1];

                arrrole.push(str);
            }
        });
        $('#myprocessCodeTags li').each(function () {
            var str = $(this).html();
            var res = str.match("<span class=\"tagit-label\">(.*?)</span>");
            if (res != null) {
                var str = res[1];

                arrpcode.push(str);
            }
        });



        console.log(JSON.stringify(arrtemplate));
        $.ajax({
            url: "/api/TagCloud/SessionTemplate",
            method: "Post",
            data:JSON.stringify( { templates : arrtemplate, roles : arrrole, pcodes :  arrpcode}),
            async: false,
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            success: function (msg) {
                console.log(msg);
                if (msg == true) {

                  //  alert("true");
                }
            }
        });




    }

        </script>

C#代码:

  [HttpPost]
    public bool SessionTemplate(string[] templates, string[] roles, string[] pcodes)
    {
        HttpContext.Current.Session["templates"] = templates;
        HttpContext.Current.Session["roles"] = roles;
        HttpContext.Current.Session["pcodes"] = pcodes;
        return true;
    }

像这样将字符串数组添加到新数组中:

//the nested array (hardcoded for clarity)
var newarray = {a:['a','b','c'],b:['d','e','f']a:['g','h','i']};
var jsondata = JSON.stringify(newarray);
//send jsondata to server

然后使用JavaScriptSerializer类在服务器端反序列化json数据:

//assign submitted json to the variable jsondata (hardcoded for clarity)
String jsondata = "{a:['a','b','c'],b:['d','e','f']a:['g','h','i']}";
JavaScriptSerializer jsonparser = new JavaScriptSerializer();
dynamic result = jsonparser.Deserialize<dynamic>(jsondata);
Respone.Write(result['a',2]); //writes 'c'

您可以使用dynamic result = jsonparser.Deserialize<dynamic>(jsondata); 如果您没有课程。
当您这样做时,可以使用MyClass result = jsonparser.Deserialize(jsondata,MyClass); 使用对象初始值设定项自动分配值并返回用值填充的类的新实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM