简体   繁体   English

循环通过JQUERY作为数组传入的对象,并使用c#webmethod来获取数据

[英]looping through an object passed in via JQUERY as an array and using c# webmethod to get data out

all, 所有,

I'm getting to my webmethod in my code behind but I'm having problems deserializing my json data. 我在我的代码中遇到了我的webmethod但是我在解析我的json数据时遇到了问题。 I have no good reference but here is what I"m trying to do. My the code in my webmethod is not allowing me to get the data out passed from my ajax call. thanks for any help. 我没有很好的参考,但这是我想要做的。我的webmethod中的代码不允许我从我的ajax调用传递数据。感谢任何帮助。

$("[id$=rdbSaveAjax1]").click(function () {

    var mappedJobRole = new Array();

    $(".jobRole").each(function (index) {

        var jobRoleIndex = index;
        var jobRoleID = $(this).attr('id');
        var jobRoleName = $(this).text();

        // add all the roleids and rolenames to the job role array.  
        var roleInfo = {
            "roleIndex": jobRoleIndex,
            "roleID": jobRoleID,
            "roleName": jobRoleName
        };

        queryStr = { "roleInfo": roleInfo };
        mappedJobRole.push(queryStr);

    });

    $.ajax({
        type: "POST",
        url: "Apage.aspx/Save_Mapped_Role",
        data: "{'savedRole': " + JSON.stringify(mappedJobRole) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data) {
            alert("successfully posted data");
        },
        error: function (data) {
            alert("failed posted data");
        }

     });

});

In my code behind I can't seem to get the data out. 在我的代码背后,我似乎无法获取数据。 My class: 我的课:

public class MappedRole
{

    public int Index { get; set; }
    public string RoleID { get; set; }
    public string RoleName { get; set; }

}

My webmethod: 我的网络方法:

[WebMethod]
public static bool Save_Mapped_Role(object savedRole)
 {
   bool success = false;
   JavaScriptSerializer js = new JavaScriptSerializer();
   IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>savedRole);
   int Index = role[0].Index;
   string RoleID = role[0].RoleID;
   string RoleName = role[0].RoleName;

    return success;

  }

This line seems to be missing an opening parenthese 这条线似乎缺少一个开头的括号

IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>savedRole);

Should read 应该读

IList<MappedRole> role = new JavaScriptSerializer().Deserialize<IList<MappedRole>>(savedRole);

Furthermore, in order to use the Deserialize method, you need to create classes based on the JSON variables you are passing. 此外,为了使用Deserialize方法,您需要根据要传递的JSON变量创建类。 For example based on the JSON object you created, you should have the two classes below. 例如,基于您创建的JSON对象,您应该具有以下两个类。

SavedRole Class SavedRole类

public class SavedRole 
{
    public roleInfo[] { get; set; }
}

roleInfo Class roleInfo类

public class roleInfo
{
    public int roleIndex { get; set; }
    public string roleID { get; set; }
    public string roleName { get; set; }
}

Now the Deserialze method will do its magic and populate the objects for you. 现在,Deserialze方法将发挥其魔力并为您填充对象。 Then you'll be able to loop through the object and do what you need with the data. 然后,您将能够遍历对象并使用数据执行所需操作。

[WebMethod]
public static bool Save_Mapped_Role(object savedRole)
{
   bool success = false;
   var serializer = new JavaScriptSerializer();
   SavedRole role = serializer.Deserialize<SavedRole>(savedRole);

   //Loop through the data like so

   int roleIndex = 0;
   string roleID = null;
   string roleName = null;

   foreach (var item in role.roleInfo) {
       roleIndex =  item.roleIndex;
       roleID = item.roleID;
       roleName = item.roleName;

       //Do more logic with captured data
   }

   return success; 
}

Hope that helps 希望有所帮助

this post explain how you can convert a JSON to C#: Parse JSON in C# 这篇文章解释了如何将JSON转换为C#: 在C#中解析JSON

If you don't want to use that, you need to do some changes in your project: 如果您不想使用它,则需要在项目中进行一些更改:

First, to get the your RoleInfo, you need to transform it in a Dictionary like: 首先,要获取您的RoleInfo,您需要在Dictionary中对其进行转换,如:

(((object[])savedRole)[0] as Dictionary<string, object>)["roleInfo"]

After that, you can manipule your object to create your List: 之后,您可以操纵对象来创建List:

    var list = ((object[])savedRole);

    IList<MappedRole> role = new List<MappedRole>();

    foreach (var item in list)
    {
        var dic = ((item as Dictionary<string, object>)["roleInfo"] as Dictionary<string, object>);

        MappedRole map = new MappedRole()
        {
            roleIndex = Convert.ToInt32(dic["roleIndex"]),
            roleID = dic["roleID"].ToString(),
            roleName = dic["roleName"].ToString()

        };

        role.Add(map);
    }

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

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