如何将字符串[]类型参数从jquery传递到asp.net web api方法?

时间:2016-05-20 06:44:17

标签: c# jquery asp.net ajax

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

string [] a,string [] b,string [] 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;
    }

1 个答案:

答案 0 :(得分:1)

将字符串数组添加到新数组中,如下所示:

//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 class

反序列化服务器端的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);使用对象初始值设定项自动分配值返回一个用值填充的类的新实例。