How to send a DOM element's value to an AJAX request using HTML.PagedList parameters

As I delve into learning ajax requests, I find myself questioning if I am on the right track. Currently, I have a page that incorporates pagination, sorting, and searching functionalities. My goal is to implement these features using ajax to avoid reloading the entire page. Below is an excerpt from my parent view:

..
<div id="nursesList">
               @Html.Partial("PaginatedNurses", Model)
</div>
...

Furthermore, here is the partial where I attempt to utilize ajax:

@using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
@using X.PagedList
@using X.PagedList.Mvc.Core
@using X.PagedList.Mvc.Core.Common
@model X.PagedList.IPagedList<Services.ViewModel.Admin.Nurse.NurseDetailsViewModel>
    <form>
    <div id="RegisteredNurses">
        <div class="form-group row">
            <div class="col-md-3">
                از سن <input class="form-control" id="minAge" type="number" name="MinAge" value="@ViewBag.MinAge" />

            </div>
            <div class="col-md-3">
                تا سن <input class="form-control" id="maxAge" type="number" name="maxAge" value="@ViewBag.MaxAge" />
            </div>
            <div class="col-md-3">
                مرتب سازی بر اساس
                <select class="form-control" name="SortOrder" value="@ViewBag.SortOrder" style="width: 200px" id="sortOrder">
                    <option value="age">
                        سن
                    </option>
                    <option value="registerDate">
                        زمان ثبت نام
                    </option>
                </select>
            </div>
            <div class="col-md-3">
                نحوه مرتب سازی
                <select class="form-control" name="SortType" value="@ViewBag.SortType" style="width: 200px" id="sortType">
                    <option value=1>
                        صعودی
                    </option>
                    <option value=0>
                        نزولی
                    </option>
                </select>
            </div>
        </div>
        <input type="submit" value="جست و جو" id="btnSearch" />
  
        ... (remaining content unchanged) ...

    </div>
    </form>
        @section modalSection
        {
            <script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
        }

The main section to focus on is as follows:

<div id="pager">
                @Html.PagedListPager((IPagedList)Model, page => Url.Action("RegisteredNurseList", new { page}),
                    PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "RegisteredNurses" }))
            </div>

To further enhance functionality, I aim to incorporate the input values into my DOM. For instance:

<div id="pager">
                @Html.PagedListPager((IPagedList)Model, page => Url.Action("RegisteredNurseList", new { page , sortOrder=('#sortOrder').val()}), 
                    PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "RegisteredNurses" }))
            </div>

While acknowledging that sortOrder=('#sortOrder').val() may not be valid code, I seek alternative solutions or better approaches. Here is an overview of my controller:

public async Task<ActionResult> RegisteredNurseList(int? page, int? sortType,string sortOrder,
            int? minAge, int? maxAge)
       {
           ... (controller logic remains unchanged) ...
            
        }

Answer №1

For those seeking assistance, my solution can be found here:

If you need to capture a user's click on a page number within a pager control and modify the link before allowing it to proceed, JavaScript can handle this client-side. Utilize an onClick handler on the page numbers. Include the following code snippet in your jQuery document ready event:

$('#pager').find('a[href]').on('click', function (e) {
    e.preventDefault();
    location.href = this.split('?')[0]
        + "?page=" + getQueryStringValue(this, 0).replace('page=','') 
        + "&sortOrder=" + $("#sortOrder").val(); // Additional values can be added if necessary
    }
});

This helper function can assist with extracting query string values:

getQueryStringValue: function (anchor, index) {
    var queryString = $(anchor).attr('href').split('?')[1];
    var values = queryString.split('&');
    return values[index];
}

The code snippet below acquires the raw URL excluding the querystring; in this context, 'this' refers to the URI:

this.split('?')[0]

Using location.href simulates clicking a link, leading to a page redirection based on the specified URI.

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

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...

Why is it that a specific variable is only undefined in one specific location within the entire component?

import React from 'react'; import { Formik, Form } from "formik"; import { InputField } from "./formui/InputField"; import { applyGharwapasi } from "../../appollo/applyGharwapasi/applyGharwapasi"; import { useMutatio ...

"Enhance User Interaction with a Bootstrap Popup when Submitting Form Data via

As a junior web master, I have a simple question to ask. I have created a single page application for a client with a contact form at the end of the page. The validation is done using Bootstrap, but the only method I know to send the form data to a mail id ...

ReactJs - Organize your data with the sort method

In my React application, I have a table that fetches its data from an API. I need to implement sorting for one of the columns. The values in this column are usually strings of numbers but sometimes can be equal to "-" (Dash). Below is the sort function I ...

Create and export a global function in your webpack configuration file (webpack.config.js) that can be accessed and utilized

Looking to dive into webpack for the first time. I am interested in exporting a global function, akin to how variables are exported using webpack.EnvironmentPlugin, in order to utilize it in typescript. Experimented with the code snippet below just to und ...

Bringing in an SVG file as a React component

When importing an SVG into React as a Component, I am facing an issue where the CSS classes are wrapped in style tags, causing an error upon import. Removing the CSS from the style tags allows the SVG to load, but it loses its additional styling. I want t ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...

Using Node.js variables outside of a function

I've been facing issues with passing my trends variable from its function into a renderer for my Pug template. It's proving to be quite challenging. var express = require('express'); ...

Converting a busboy file stream into a binary object in Node.js: A step-by-step guide

Seeking assistance with image file upload functionality by integrating Express and Node.js. Currently, I am utilizing the Busboy package to receive binary data in a file format. Specifically, my inquiry revolves around understanding how to capture this bi ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Tips for gradually increasing numerical values line by line

Plunker. After implementing the Plunker provided above, I noticed that the rowId is increasing with alphabets, as shown below: The component in the Plunker contains buttons labeled with +, ++, and -. When you press the + button, the rowId starts from the ...

Loading asp.net controls dynamically using JavaScript

In the process of creating ASP.NET controls that facilitate the development of dynamically generated websites based on a class.cs file, these controls are loaded into a Placeholder within an update panel. My goal is to leverage technologies like AJAX and ...

Trigger a personalized URL while making an ajax call

I was attempting to run an AJAX request (file: ajax.php) and desire to trigger another custom URL from ajax.php while the AJAX call is in progress. I experimented with CURL for this purpose, but unfortunately, it did not yield favorable results. If someo ...

Replace particular letters within the text with designated spans

Suppose I have this specific HTML code snippet: <div class="answers"> He<b>y</b> <span class='doesntmatter'>eve</span>ryone </div> Additionally, imagine I possess the subsequent array: ['correct' ...

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

Exploring AngularJS: the power of directives and the art of dependency

According to Angular documentation, the recommended way to add a dependency is by following these steps: Source //inject directives and services. var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl&ap ...