【问题标题】:how to return two array list in JSON and view in data table rows using asp.net MVC?如何在 JSON 中返回两个数组列表并使用 asp.net MVC 在数据表行中查看?
【发布时间】:2018-05-20 05:54:48
【问题描述】:

RoleList 和 EmpList 我们有两个arraylist 如何在JSON 中返回两个array list 以及如何在数据表行中查看。

我需要回return Json(EmpList,RoleList, JsonRequestBehavior.AllowGet);

[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
            }

            return Json(EmpList, JsonRequestBehavior.AllowGet);

        }

脚本:

<script>
        $(document).ready(function () {

            $("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data, function (i, item) {
                            $("#findValue").show();
                            var rows = "<tr>"
                            + "<td>" + i + "</td>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + item.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
        });
    </script>

cshtml:

<table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
                        <thead>
                            <tr>
                                <th>S#</th>
                                <th>Module Name</th>
                                <th>Url</th>
                                <th>Roles</th>
                                @*<th>Action</th>*@
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>

在我的代码中只返回一个数组列表..

我需要显示到数组列表

public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }


        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }

【问题讨论】:

  • 您可以执行return Json(new { empList = EmpList, roleList = RoleList }, , JsonRequestBehavior.AllowGet); 之类的操作并访问data.empListdata.roleList 之类的操作
  • 请注意,在最后一个 foreach 中,您在每次迭代时都会覆盖 RoleList 的值。也许您想在此列表中添加内容?
  • @Andrei 是的 RoleList 是局部变量,所以显示一些错误
  • 好吧,显然你应该初始化它。我希望它用一个空列表初始化,然后在每次迭代中添加东西

标签: javascript asp.net ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以轻松地将两者与匿名类型结合起来:

var data = new {EmpList = EmpList, RoleList = RoleList};
return Json(data, JsonRequestBehavior.AllowGet);

在客户端只需使用您需要的属性:

success: function (data) {
    // do something with role list
    $.each(data.RoleList, function (i, item) {

    ...
    // do something else with employee list
    $.each(data.EmpList, function (i, item) {

【讨论】:

  • 列表 角色列表;使用未分配的 RoleList 显示错误
  • @IvinRaj,你当然应该给它赋值
  • List RoleList = new List ();我在这段代码中添加是正确的吗? @安德烈
  • @IvinRaj,是的,假设您稍后还会在其中添加一些项目
  • $.each(data.RoleList, data.RoleList in foreach 函数我们可以将结果显示为单行@Andrei
【解决方案2】:

您可以尝试使用字典的简单方法。

     public ActionResult ViewModules(int id)
    {
        Domain_Bind();
        dynamic mymodel = new ExpandoObject();
        userType type = new userType();

         Dictionary<string, object> dList = new Dictionary<string, object>();

        List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
        string sRptModuleIDs = string.Empty;
        foreach (ViewRoleModules emp in EmpList)
        {
            sRptModuleIDs += emp.ModuleID + ",";
        }
        if (sRptModuleIDs != "")
        {
            sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
        }

        List<ViewRoleModules> RoleList;
        foreach (var rid in sRptModuleIDs.Split(','))
        {
            string RID = rid;
            RoleList = type.GetSiteRoleModulesViews(rid);
        }

        dList.Add("EmpList", EmpList);
        dList.Add("RoleList", RoleList);

        return Json(dList, JsonRequestBehavior.AllowGet);

    }

借助字典,可以将n个对象绑定在一起。

【讨论】:

  • 列表 角色列表;使用未分配的 RoleList 显示错误
  • 你可以试试 List RoleList = new List ();和 RoleList .Add(type.GetSiteRoleModulesViews(rid));
  • 数据行查看如何调用dList
  • @lvin Raj EmpList.propertyName like EmpList.firstName
  • item.ModuleName 是默认使用,如果我更改 EmpList.ModuleName 是无法获取值
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多