Binding multiple items in ASP.NET MVCIncorporating arrays with

Utilizing Tablesorter and in the process of implementing server-side paging through Ajax. Tablesorter enables sorting on multiple columns and utilizes this URL structure when clicking on the first column:

http://example.com/tablesorter/json?page=0&size=25&column[0]=1

The above scenario functions correctly with my current (Tablesorter) controller action:

public JsonResult Json(int page, int size, int[] column)

However, if I solely sort by the second column, the following URL is triggered which leads to a null value for the column parameter. I suspect this is due to a missing zero-index value.

http://example.com/tablesorter/json?page=0&size=25&column[1]=1

Therefore, my inquiry is: Is it possible to model bind the Tablesorter format using a different data type or will adjustments need to be made to Tablesorter's URL pattern?

For sorting by multiple columns, the format should be as follows:

http://example.com/tablesorter/json?page=0&size=25&column[0]=1&column[1]=1

Answer №1

Customize the ajax url using the customAjaxUrl option as needed.

Consider utilizing jQuery's $.param() function for assistance.

ajaxUrl: 'http://example.com/tablesorter/json?page={page}&size={size}',
customAjaxUrl: function(table, url) {
    // sortList = [[1,0], [2,0]]
    var sort = $.param({ column : table.config.sortList });
    // result: "column[0][]=1&column[0][]=0&column[1][]=2&column[1][]=0"
    return url + '&' + sort;
}

If the current format is not suitable, consider adjusting on the server side.


If specifying all columns is necessary, try this code:

ajaxUrl: 'http://example.com/tablesorter/json?page={page}&size={size}',
customAjaxUrl: function(table, url) {
    var i, v,
    c = table.config,
    s = c.sortList; // sortList = [[1,0], [2,0]]
    for (i = 0; i < c.columns; i++){
        v = 2;
        if ($.tablesorter.isValueInArray(i, s)) {
            $.each(s, function(j){ 
                if (s[j] && s[j][0] === i) {
                    v = s[j][1];
                }
            });
        }
        // 0 = ascending; 1 = descending; 2 = unsorted
        url += '&column[' + i + ']=' + v;
    }
    // result: "&column[0]=2&column[1]=0&column[2]=0&column[3]=2&column[4]=2"
    return url;
}

If the above solutions do not work, further investigation may be required regarding ASP.NET & model binding. Refer to this answer for additional insights.

Answer №2

Although this may be an older method, I collaborated with Mottie's solution and made some improvements.

customAjaxUrl: function(table, url) {
    // create sort list
    var config = table.config;
    var sortList = config.sortList;

    for (var i = 0; i < config.columns; i++){
        var v = 2;

        $.each(sortList, function(j, item){ 
            if (item && item[0] === i) {
                v = item[1];
            }
        });

        // 0 = ascending; 1 = descending; 2 = unsorted
        url += '&sortColumn[' + i + ']=' + v;
    }

    // create filter list
    var filterList = config.pager.currentFilters;

    for (var i = 0; i < filterList.length; i++) {
        url += '&filterColumn[' + i + ']=' + filterList[i];
    }

    return url;
},

The declaration of my MVC action looks similar to this:

public ActionResult ListByPage(int page, int size, List<int> sortColumn, List<string> filterColumn)
{
}

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

oidc-client-js consistently redirects users to the login page

I've been immersed in a project that involves integrating OIDC authentication into a react SPA using authorization code with PKCE. I'm utilizing the oidc-client-js library for this purpose. The issue I'm facing is that, post-authentication, ...

how to execute a javascript function in an ionic controller from the template

My journey in creating my first Ionic app has been smooth so far. I am not well-versed in UI design, so I may not be implementing the best practices, but I am making progress nonetheless... Within a template, I have encountered the following code snippet ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

Creating an IntersectionObserver with the Composition API: A Step-by-Step Guide

I am currently in the process of incorporating an IntersectionOberver that will update the url once the viewport transitions into a new section. I came across This thread and now endeavoring to apply it in vue 3 compositon api. The script is being integra ...

Is it possible to utilize multiple .html files in a single view while incorporating Materialize?

Within my AngularJS application that utilizes Materialize, I have a module called "reports" containing a view called "reports.html" intended to house all of my reports. However, I desire to separate the code for each report into individual .html files, suc ...

Click event not triggering for selected option in jQuery dropdown menu

After adding dropdown anchor tags dynamically to the drop-down menu, the click event does not seem to be firing. Do I need to re-bind the click handler after using .append, or should I wrap the click handler in a function? <script src="https://code.jqu ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Can JavaScript be used to iterate through the id attribute of an image tag?

Check out my amazing code snippet created with HTML and Javascript: <html> <body> <img id="img0" style="position:fixed; width:116px; height:100px;" > <img id="img1" style="position:fixed; width:116px; height:100px;" > ...

Is it feasible in Angular2 to add CSS to a component using a service?

I have a component named A containing 5 images. Out of the 5, only one image is in color and clickable, while the remaining 4 are greyed out using the CSS class below: .not_opened{ -webkit-filter: grayscale(85%); } The greyscale images are not clickabl ...

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

What is the process of allocating a function to a question within a POST request?

Is it possible to assign the function renderAnswers() to a question in a POST request? How can I do this correctly for it to work as intended? methods: { renderAnswers() { let answers = this.question; let newAnswers = answers.map(( ...

Tips for optimizing nested object array searches

Is there a widely recognized technique to chain .map or .filter or .find functions in order to achieve this type of search? Imagine an array of objects nested within another array of objects customerGroups : [ { id: 1, customers: [{ id ...

Tips for importing native JS files on a single page in nuxtJS

When attempting to import my local JS file into the "head" section of the nuxt.config.js file, I encountered an error. Interestingly enough, importing the "CDN" file in the same location worked perfectly fine. ...

Use javascript to retrieve multiple images from the server using XMLHttpRequest

Currently, I am successfully using the XMLHttpRequest method to obtain the URL of a single image from the server in order to download, save, and retrieve it from Android local storage. However, I have hit a roadblock when attempting to figure out how to do ...

Customize the Width of DropDown List Items with Razor

I'm having trouble adjusting the width of items in a DropDownList. I want the width of the DropDown items to be different from the DropDown itself. Can anyone assist me with this? <div class="col-md-3"> @f.FormGroup().DropDownList("IdTipoAc ...

I am unable to utilize the MQTT.js node package through a CDN

After installing mosquitto, I located it in the directory path: C:\Program Files\mosquitto Next, I started mosquitto by running the command: mosquitto.exe Then, I inserted the following code into the "test.html" file: <script src="https ...

Tips for positioning input fields and labels in both horizontal and vertical alignment

Below is the HTML code, and I want the tags to look like this: label1: input1 label2: input2 label3: input3 Instead, it currently looks like this: label1: input1 How can I modify the HTML to achieve the desired format? HTML: <div class=" ...

Having trouble setting Camera.rotation in three.js version 73?

After placing the camera in position during initialization, I noticed that there were no visible changes. I also implemented Orbital controls within the same function. Camera.rotation.x = 90*Math.PI/180; ...

Accessing an array within a function from a separate .JS file

Currently, I am facing a somewhat awkward predicament where I have a function in main.js that requires an array that is populated in second.js... In simple terms, the function in main.js is designed to be reusable: function chug() { p1.innerHTML = st ...

display pictures on the screen through the use of web addresses

Having trouble displaying images from Flickr on the screen using URLs. Can't seem to get any images to show. Check out the code snippet below: loadimages(e) { e.preventDefault(); this.setState({spinner:true}); console.log('spinner') ...