Are Viewmodel contents empty after ajax request?

Currently working on an ASP.NET MVC application, I am in the process of developing a search page that showcases both the search box and the table of results simultaneously. To achieve this functionality, I have utilized Partial Views along with AJAX/JSON calls utilizing a viewmodel. However, upon passing the two search terms through ajax, they seem to be null in the controller.

Below is the code snippet:

ViewModel:

public class ExampleViewModel
{
    public string search { get; set; }
    public string search2 { get; set; }

}

Controller:

[HttpPost]
    public ActionResult Search(ExampleViewModel searchTerm)
    {
        var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));

        return PartialView("_SearchResultsPartial", searchList);
    }

Body of Index View:

<body>
<div>
    @Html.TextBoxFor(model => model.search)
    @Html.TextBoxFor(model => model.search2)
    <input type="submit" value="Search" onclick="return getSearchResults()"/>

</div>

<div id="search-results">

</div>

<script>
    var exViewModel = {
        search: $('#search').val(),
        search2: $('#search2').val()
    }

    function getSearchResults() {        

    $.ajax({
        type: "POST",
        data: JSON.stringify(exViewModel),
        dataType: "json",
        contentType: "application/json",
        url : "/View/Search/",
        success: function (result) {
            $("#search-results").html(result);
        }
    });
    }


</script>

Even after establishing a breakpoint on the Search [POST] method, it appears that the ExampleViewModel's terms are null.

Answer №1

Upon initial inspection, it appears that the values need to be retrieved within the function's scope:

function fetchSearchResults() {        
    // Obtain these values when button is clicked
    var searchValues = { 
        search: $('#search').val(),
        search2: $('#search2').val()
    }

    $.ajax({
        type: "POST",
        data: JSON.stringify(searchValues),
        dataType: "json",
        contentType: "application/json",
        url : "/View/Search/",
        success: function (result) {
            $("#search-results").html(result);
        }
    });
}

Otherwise, the searchValues are only set during page load.

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

Fetch the Future<list<DATA>> array from an API in Flutter and parse the JSON response

I recently dove into Flutter and decided to start using FlutKit packages. I've encountered a challenge with an array LIST while working on this project. FlutKit utilizes a list with static Json data to cache initial data, including Products, Categorie ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

What is causing the issue preventing me from running npm run dev on CentOS 7?

Currently facing an issue while trying to install my application on a new server after migrating from centos6 to centos7. When attempting to install a Laravel app, everything goes smoothly as it did on centos6, except for when I run npm run dev [root@v6-a ...

Guide on incorporating labels to vertices within GRAPHSON, a JSON dependent format designed for graph components

Exploring the link, I am seeking guidance on how to label vertices in a JSON file to optimize graph traversals. My current setup includes using Titan graph DB, where GRAPHSON conversion and Gremlin query language are utilized. To enhance vertex retrieval s ...

Is it possible to integrate payment methods such as PayPal or Stripe in Vue.js without using a server like Express? If so, how can I implement this

After completing the development of my web shop in Vue.js, I realized that the payment method is still missing. I am wondering if I need to integrate Express in order to process payments through Stripe? Currently, I do not have a server like Express set up ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

Avoiding Vue Select from automatically highlighting the initial option: tips and tricks

Currently utilizing Vue Select as a typeahead feature that communicates with the server via AJAX. By default, the first option from the server response is highlighted like this: https://i.stack.imgur.com/jL6s0.png However, I prefer it to function simila ...

How can I implement an autocomplete feature in Vue.js?

Recently, I started working with Vue and decided to create a basic search app using Vue.js cdn. My goal is to add a suggestion bar that displays user IDs from a fake JSON server. For instance, if I input '1' in the search bar, I want only the use ...

How to fetch React route parameters on the server-side aspect

I encountered a challenge while working with ReactJS and ExpressJS. The user uploads some information on the /info route using React and axios. Then, the user receives route parameters from the server side to redirect to: axios.post('/info', Som ...

Is there a way to receive live updates for records in real-time using push notifications?

I am in the process of developing a Ruby on Rails ecommerce platform that enables potential customers to place orders while allowing the store owner to receive them instantaneously. Once an order is finalized, it will be saved into the database (currently ...

What is the best way to extract the JSON data from a client-side GET request response?

Here is my request from the client side to the server in order to retrieve JSON data. fetch("/" + "?foo=bar", { method: "GET", }).then(response => { console.log(" ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

I created a thorough duplicate that successfully addressed an issue with a table

Currently, I am facing an issue with the material-table library as it automatically adds a new element called tableData to my object when I update it using Patch in my code and API. To resolve this problem, I tried implementing both a conventional and cust ...

Tips for effectively utilizing the select feature with Firebase data within the Angular UI typeahead functionality

I am currently attempting to integrate Angular-UI typeahead with data retrieved from my Firebase database. The structure of the data is as follows: Data:{ "-JL8IPEAs0vLSt4DJ4V9": { "name": "Something" }, "-JL8IbggYn3O8jkWoPmv": { "name": "Something Els ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Variability in the values returned by the useState hook

Currently, I am working on developing my initial user signup form, and I have encountered a challenge that seems relatively simple to resolve but goes beyond my current expertise. The issue pertains to the helperText for an MUI select component which is no ...

The process of filtering JSON data in Angular can be easily achieved by utilizing the filter functionality

Seeking recommendations for useful books or online resources to learn how to filter JSON data effectively using angular filters. Interested in tackling more complex datasets. Any assistance on this matter would be greatly appreciated. ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

Sticky positioning causes elements to stick to the window as the

https://i.stack.imgur.com/nv3vU.png I am facing an issue with a position sticky block that can vary in height relative to the window size. Sometimes, the block is taller than the viewport, making it impossible to scroll to see all the content. Is there a ...

Generating a generic list in C# using JArray

Currently, I am facing a challenge with my dynamic import process that involves converting Json into an object array. My main obstacle lies in creating a List<> based on a string reference to the class object. To elaborate, I am retrieving json data from ...