Send a string to the controller through an AJAX request

Seeking assistance on creating a search field to find users within my system. The idea is to input the user's name into the field, then use an Ajax function to pass that name from the search field to a method in the controller. This method will return an enumerable list of all users with the same name. When passing the user ID, everything works flawlessly as it expects an integer value. However, when passing a string (the user's name), issues arise. How can I correctly pass the user's name to the controller using Ajax?

Below are the view tags:

    <div class="form-group">
        <label asp-for="ResearchAuthor.ApplicationUserId" class="control-label"></label>
        <input id="user"  asp-for="ResearchAuthor.ApplicationUserId" class="form-control" asp-items="ViewBag.ApplicationUserId" />
        <a id="srch" class="btn btn-success">Search</a>
    </div>
    <select id="add" asp-for="ResearchAuthor.ApplicationUserId" class="form-control" asp-items="ViewBag.ApplicationUserId">
        <option>Select User</option>
    </select>

Ajax code snippet:

       <script>
    $("#add").empty();

    $(document).ready(function () {
        $("#srch").click(function () {
            $("#add").empty();
            $("#add").append($('<option>', { text: "Select Article Type" }));
                var useroptions = {};
            useroptions.url = "/@CultureInfo.CurrentCulture.Name/ResearchAuthors/GetUsers/";
            useroptions.data = JSON.stringify($("#user").val());
                useroptions.success =  function (data) {
                    $.each(data, function (index, row) {
                        $("#add").append($('<option>', { value: row.value, text: row.text }))
                    });
                };
                useroptions.error = function () { alert("An Error Occurred"); };
                $.ajax(useroptions);
            
        });
    });
</script>

The corresponding function in the controller:

   [AllowAnonymous]
    public JsonResult GetUsers(string SearchString)
    {
        var users = new SelectList(_context.ApplicationUsers.Where(u=>u.ArName==SearchString), "Id", "ArName");
        return Json(users);
    }

Answer №1

Before proceeding, always remember to validate the data in the backend code. If the value is an integer, you can proceed as normal. However, if it is a string, make sure to convert it into an integer if feasible.

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

Using jQuery to deactivate the submit button when a field is empty or a checkbox is left unchecked

Today is my first attempt at using jQuery, and I could really use some assistance as I'm struggling to achieve the desired outcome. I'm dealing with a table of documents, each containing a checkbox for selection purposes. Additionally, there&apo ...

Is it possible to invoke a controller's function using my JavaScript code located in the assets directory?

Currently, I am developing a project using Ruby on Rails. Within my app folder, I have organized my files into four main folders: models, views, controllers, and assets. Specifically in the assets folder, I have some JavaScript code that runs whenever vi ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

Using jQuery to Send a POST Request and Delete a File when a Button is

Seeking assistance for a project I'm working on. I have created this page where users can access an image gallery. Currently, I am adding a feature to allow users to delete images. Following advice from the community here here, I am exploring the jQ ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Determine whether a subdomain is present within an ajax file in php

Looking for assistance with checking the existence of a 'Subdomain' in a file called '\example\sites'. Here's the code: $form = array() ; $form['name'] = "install"; $form['action'] = "?step=2"; $for ...

Ways to expand the border horizontally using CSS animation from the middle

Currently, I am experimenting with CSS animation and I have a query regarding creating a vertical line that automatically grows in length when the page is loaded. I am interested in making the vertical line expand from the center in both upward and downwar ...

Employing on() for triggering a form submission

I am attempting to attach a submit event handler to a form that may not always be present in the DOM, so I am using .on(): $('body').on("form","submit", function(e){}) However, when checking Firebug, it shows: $("body").on is not a function ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Using CakePHP4: Transmit Data via Ajax from Controller to View

I'm trying to retrieve data from the database and send it using Ajax in CakePhp4 from the controller to the view. Although I've managed to implement it (with sparse documentation), I'm facing an issue where it doesn't return me the arr ...

Is it possible to assign the margin-bottom property of one element to be equal to the dynamic height of a sibling element?

I am in the process of creating a website that features a fixed (non-sticky) footer placed behind the main content using the z-index property. The footer only becomes visible when the user scrolls to the bottom of the page, achieved by assigning a margin-b ...

Switch out either even or odd divs within a container

I need help figuring out how to alternate the background colors of divs within a container. I want the first one to have a red background, the second to have blue, the third red again, and so on... Here is the code I currently have: <div>...</di ...

Using jQuery AJAX to apply filters to forms and update URL hashes

I have coded the following snippets: <label class='checkbox'><input type='checkbox' class='custom_filter' name='kleuren' value='Blauw' data-taxonomy='kleuren' data-category='Bla ...

ways to undo modifications made to a value within an input field using jquery or javascript

$(document).ready(function () { //Highlight row when selected. $(function () { $('#Cases tr').click(function () { $('#Cases tr').removeClass('selectedRow'); $(this).addClass(&apos ...

Creating a dynamic line chart in Primefaces that updates every second in JSF 2

I'm looking to create a dynamic webpage featuring a Primefaces line chart that updates every second. Currently, I retrieve 100 data points from my database in the managed bean. Rather than loading all the data at once onto the line chart, I would lik ...