Using the MVC framework to implement paging and filtering, the view model parameters are passed to the action

I am currently developing a search feature that involves passing options through a filter view model:

public class FilterViewModel
{
    public string UserName { get; set; }

    public int? TownId { get; set; }

    [Display(Name = "Gender:")]
    public bool? IsMale { get; set; }

    [Display(Name = "Interests:")]
    public int[] InterestsIds { get; set; }

    public List<ProfileInterest> Interests { get; set; }

    ...

}

The use of Ajax is employed to call the action:

[HttpPost]
public ActionResult FilterProfiles(FilterViewModel filter)
{
   //This method retrieves the filtered items and returns a partial view     
   ...
}

I am searching for a library that can assist with pagination in conjunction with managing Ajax requests and view model parameters passed to the action.

Appreciate your help!

Answer №1

I found MvcPaging to be quite helpful. By following the examples provided, I was able to implement it successfully.

When working with the filter view model, I made sure to include a 'Page' property:

    public class FilterViewModel
    {
        public int? Page { get; set; }

        public string UserName { get; set; }

        public int? TownId { get; set; }

        [Display(Name = "Gender:")]
        public bool? IsMale { get; set; }

        [Display(Name = "Interests:")]
        public int[] InterestsIds { get; set; }

        ...

    }

I then proceeded to create a new view model to store both the search results in IPagedList and the filter options:

public class CurrentFilterViewModel
{
    // Stores the search result items
    public IPagedList<ProfileViewModel> Profiles { get; set; }

    public string UserName { get; set; }

    public string LastName { get; set; }

    public int? TownId { get; set; }

    public bool? IsMale { get; set; }

    public int[] InterestsIds { get; set; }

    ...

}

In the controller action, I passed the search results and filter properties values to the respective properties of the current model:

    [HttpPost]
    public ActionResult FilterProfiles(FilterViewModel filter)
    {
        var filteredProfilesModel = new CurrentFilterViewModel();
        filteredProfilesModel.UserName = filter.UserName ?? null;
        filteredProfilesModel.TownId = filter.TownId ?? null;
        filteredProfilesModel.IsMale = filter.IsMale ?? null;
        filteredProfilesModel.InterestsIds = filter.InterestsIds ?? new int[0];

        int DefaultPageSize = 3;
        int currentPageIndex = filter.Page.HasValue ? filter.Page.Value - 1 : 0;

        filteredProfilesModel.Profiles = 
        // ... retrieve the matching items from the database ...
        .ToPagedList(currentPageIndex, DefaultPageSize);

        return this.PartialView("_FilterProfilesPartial", filteredProfilesModel);
    }

Additionally, on the partial view loaded via AJAX, I implemented pagination functionality by setting up the paging system and mapping the filter parameter values to the corresponding model properties. I utilized AddRouteValueFor for maintaining the array of selected item IDs.

@using MvcPaging;
@using System.Linq;
@model Project.Web.ViewModels.CurrentFilterViewModel

    <div class="pager">
        @Html.Pager(Model.Profiles.PageSize, Model.Profiles.PageNumber, Model.Profiles.TotalItemCount,
        new AjaxOptions
               {
                   UpdateTargetId = "profiles",
                   HttpMethod = "POST"
               }).Options(o => o
                   .Action("FilterProfiles")
                   .AddRouteValueFor(m => m.InterestsIds)
                   .AddRouteValue("UserName", Model.FirstName)
                   .AddRouteValue("TownId", Model.TownId)
                   .AddRouteValue("IsMale", Model.IsMale)
                   )
    </div>

This approach proved effective for me. While I'm satisfied with the outcome, I am open to exploring potentially more elegant solutions if they exist.

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

TokenMismatchException is encountered while making an Ajax POST request in Vue-Resource

Just a heads up, I'm working with the Laravel framework. I've already checked similar questions on SO, but couldn't find a solution that worked for me... Even though I believe I've set my CSRF token correctly, it's still not funct ...

`Displaying Data in CKEditor from an Ajax Response`

I have encountered an issue with using CKEditor in Laravel 8 where I cannot display data in CKEditor from an Ajax call. Here is the code snippet for my Ajax request: $('.edit').on('click', function() { var id = $(this). ...

Searching for the value of a data attribute using an AJAX GET request

I am looking to apply styles based on the data attribute value matching an AJAX get request Here is my jQuery code: jQuery(function($) { get_stock(); function get_stock(){ $.ajax({ url: vdisain_vd.url, ...

Retrieving information from PHP using AJAX

As a newcomer to the world of AJAX, I am faced with the task of retrieving data from a PHP file and storing it in a JavaScript variable. Despite exploring several examples, I have not been able to find a satisfactory solution. Here is a simplified HTML cod ...

Retrieving a file from FormData using ExpressJS

I am new to utilizing ExpressJS for file uploads and sending data through AJAX post as FormData object. I have successfully posted from the front end, but I am having trouble retrieving the data on the server side. Here is the code snippet that I have att ...

Windows Mobile 6 HTTP server designed specifically for smooth and efficient communication

I'm currently facing a challenge with my mobile web app that runs on Opera Mobile 10 using Windows Mobile 6.5 Professional on a Motorola MC9500 device. Unfortunately, IE Mobile 6 doesn't support the required canvas element and sufficient JavaScri ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

Are you experimenting with a web application by utilizing jUnit or another API?

Is it feasible to develop a testing suite for evaluating a web application with the junit API without incorporating additional APIs or considering alternative options? Can this also handle ajax, jquery, and javascript components? In other words, will I b ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

The function $.ajax may not be available, but rest assured that the jquery library is functioning properly

Upon checking the console, I noticed the following: Here is the AJAX code snippet in use: $("#accept").click(function(){ id = $("#idInput").val(); password = $("#passwordInput").val(); alert(id) alert(password) $.aja ...

Unable to modify the appearance of an HTML element when injected via a Chrome extension

I am currently developing a unique chrome extension that uses Ajax to inject custom HTML into the current tab. This extension appends a <div> element to the body, and now I need to manipulate it using JavaScript. Specifically, I want it to dynamical ...

Exploring the relationship between Drupal and Ajax

I'm facing an issue with a custom module that creates a table with buttons, triggers an Ajax call to load a form in a div when clicked. The hook menu responsible for this function is /myapp/get_form. The problem arises when I try to save data from th ...

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

How can I implement a AJAX GET request with a parameter in ASP.Net Core 2 Razor

Is there a way to send an AJAX GET request in my ASP.Net Core 2 Razor Application with a parameter that needs to be passed to the destination function? For instance, I have a Select field in my HTML. Depending on what value is selected, I want to retrieve ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

Tips for resolving issues with PHP that is triggered by an ajax event

My index.html file includes a button that triggers an ajax request and launches a php file. The php file is supposed to send data to the server, but I am having trouble debugging it. Using echo doesn't seem to work as expected, so I'm looking for ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Transfer information from python-cgi to AJAX

Currently, I am in the process of creating a UI version of the find command found in Linux. In this implementation, I receive the location and filename parameters for the find command through a CGI form that has been built using Python. When the user submi ...

Error message displayed in jQuery dialog box

My dilemma arises when attempting to continuously call a dialog box for displaying and submitting an enquiry form on my website. Upon the first submission, everything seamlessly goes through. However, clicking the GO button (as shown in the HTML below) tri ...