What is the best way to display two array lists in JSON format and view them in data table rows using ASP.NET MVC?

There are two array lists, RoleList and EmpList. How can I return both arrays in JSON format and display them in rows on a data table?

In order to return both arrays, you can use the following code snippet:

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);

        }

Scripts:

<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>
                               
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>

The current code only returns one array list, but you need to display two array lists.

To achieve this, you can use the following methods:

public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            // Code for getting and formatting EmpList
        }


        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
           // Code for getting and formatting RoleList
        }

Answer №1

To effortlessly merge the two, utilize an anonymous type:

var mergedData = new {Employees = EmployeesList, Roles = RoleList};
return Json(mergedData, JsonRequestBehavior.AllowGet);

Then on the client side, access the specific property you require:

success: function (result) {
    // execute actions with roles list
    $.each(result.Roles, function (index, role) {

    ...
    
    // perform additional tasks with employees list
    $.each(result.Employees, function (index, emp) {

Answer №2

If you're looking for a straightforward solution, consider using a dictionary.

     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);

    }

Using a dictionary allows you to efficiently link multiple objects together.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for a solution to fix the VueJS calculator that only works once?

My calculator project using VueJS, HTML and CSS is almost complete. However, I'm facing an issue where it only works once. For example, if I input 6x3, it correctly gives me 18. But if I then clear the result and try to input a new calculation like 3 ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Exploring the combination of ASP.NET MVC with jQuery for handling file uploads through

Recently, I encountered an interesting challenge while working on a form. The form consisted of text inputs as well as a file input field. Instead of directly sending the form data using a post method, I decided to use jQuery to read each value from the te ...

Using data binding in VueJS to construct a dynamic URL

Exploring VueJS for the first time and it's been a great experience so far. However, I'm facing a couple of challenges with data binding. The requirement is for the customer to input an image URL, and no image should be displayed until a valid ...

What could be causing my JavaScript loop to only display the final value?

Story Behind the Game In my latest project, I am delving into the world of creating a captivating 2D side-scrolling game using HTML and JavaScript. To ensure smooth gameplay, I have opted to incorporate ES6 for efficient management of all game objects. C ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

Is Joomla equipped with shortcodes akin to those found in Wordpress?

One of the great features of WordPress is the ability to use shortcodes to insert information into HTML without the need for programming knowledge in PHP or JavaScript. This simplifies tasks and increases safety. For example (this is just a hypothetical s ...

Does Somebody Possess a Fine Floating Tag?

Some time ago, I came across this floating label that I have been searching for ever since. I experimented with a few that appeared promising and initially worked well, but they ended up presenting their own issues. Some required the mandatory attribute f ...

Guide on Validating a Bearer Token in ASP.NET Identity 2.0

Currently, I have an ASP.NET WEB API (project 1) that utilizes Asp.Net Identity 2.0 for user authentication. This API is specifically designed for authentication and authorization purposes. Additionally, I have two other projects: An ASP.NET MVC 5 proje ...

CORS error: The 'Access-Control-Allow-Origin' header is missing

I have a website that is being accessed through multiple domain names. Let's say the main hosted website is example.com and the forwarded domain names are example-x.com, example-y.com, example-z.com When visitors access the forwarded domains, there ...

Copying a Pinia state Array without referencing it is not possible

My goal is to duplicate an array within a Pinia store so that I can use it to create a reactive object in various components for input modeling. The intention is to only update the original array if the user decides to save any changes made using the copy ...

Passing multiple arguments to a callback function in node-js without using promises

Within my small program, I am working on unshortening a URL and then verifying if the link adheres to a specific pattern. If it meets the criteria, I aim to carry out additional processing steps. However, I find it cumbersome to pass along all 3 paramete ...

Getting data from an API using a Bearer Token with React Hooks

I am currently developing a React application that is responsible for fetching data from an API. This API requires Bearer Token Authorization. To handle this, I have implemented useState() hooks for both the token and the requested object. Additionally, th ...

Why does the selectedItems in the AngularJS grid keep coming back as undefined?

Is there a specific reason why the angularjs grid in my sample isn't displaying the selectedItems properly? Every time I attempt to reference the selectedItems, it returns "undefined." I have tested this in both Chrome and IE with identical outcomes. ...

Ensure you make a backup of the target directory before allowing files to be transferred by the msi Installer

In order to successfully deploy my ASP.NET application using a regular Visual Studio Setup Project, I need to address the issue of an existing web.config file in the target directory. If an old web.config file is found, it must be renamed before the inst ...

The art of breathing life into UpdatePanels

Although I have experimented with the UpdatePanelAnimationExtender from the Ajax Control Toolkit, my main issue with it is that it does not wait for the animation to finish before loading new content. What I aspire to achieve is: Commence asynchronous r ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Execute the file separately using dot.js

When working on my project, I decided to include a header.def file in index.dot by using the {{#def.header}} snippet. To render the index.dot file, I utilized the following snippet: var dotjs = require('dot'); var dots = dotjs.process({ path: ". ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

Acquiring the specific checkbox value using JQuery

I am encountering an issue with my JQuery function that is supposed to print out the unique value assigned to each checkbox when clicked. Instead of displaying the correct values, it only prints out '1'. Each checkbox is assigned an item.id based ...