Transferring information from View to Action

How can data be sent from the view to the controller?

This is the select element where the data is retrieved (sel1):

<div class="form-group" style="margin: 0 auto;">
            <label for="sel1">Select a cat breed:</label>
            <select class="form-control" id="sel1">
                @foreach (var item in Model)
                {
                    <option>
                        @Html.DisplayFor(modelItem => item.BreedName)
                    </option>
                }
            </select>
        </div>

This is the script attempted to send back the data:

<script>
$(document).ready(function () {
    loadJasonData();
    $("#sel1").change(function () {
        loadJasonData();
    });
});

function loadJasonData() {
    $.ajax({
        type: "POST",
        url: "CatDetails",
        //url: "/CatCompare/CatDetails", i also tried this of url
        cache: false,
        dataType: "json",
         data: { name: $("#sel1").val() }
    })
}

And here is the controller handling the data:

    [HttpPost]
    [HttpGet]
    public ActionResult CatDetails(string name)
    {
        var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);

        ViewBag.name = breedName.BreedName;
        ViewBag.lifeSpan = breedName.Lifespan;
        ViewBag.height = breedName.Height;
        ViewBag.weight = breedName.Weight;
        ViewBag.shortDescription = breedName.ShortDescription;
        return View();
    }

Answer №1

To begin, you need to include the option value in your select:

 <div class="form-group" style="margin: 0 auto;">
            <label for="sel1">Select a cat breed:</label>
            <select class="form-control" id="sel1">
                @foreach (var item in Model)
                {
                    <option value='@item.BreedName'>
                        @Html.DisplayFor(modelItem => item.BreedName)
                    </option>
                }
            </select>
        </div>

Next, update your loadJasonData() method as follows:

function loadJasonData() {
    $.ajax({
        type: "POST",           
        url: "/CatCompare/CatDetails",
        cache: false,
        dataType: "json",
         data: { name: $("#sel1 option:selected").val() }
    })
}

Finally, remove the [HttpGet] attribute from your action method:

  [HttpPost]

  public ActionResult CatDetails(string name)
    {
        var breedName = db.Breeds.FirstOrDefault(b => b.BreedName == name);

        ViewBag.name = breedName.BreedName;
        ViewBag.lifeSpan = breedName.Lifespan;
        ViewBag.height = breedName.Height;
        ViewBag.weight = breedName.Weight;
        ViewBag.shortDescription = breedName.ShortDescription;
        return View();
    }

Note: Your action method returns a view. If you want to return a JSON result, use return Json(yourData);

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

Executing a function from another reducer using React and redux

My application consists of two main components: the Market and the Status. The Status component manages the user's money, while the Market component contains buttons for purchasing items. My goal is to decrement the user's money when a button in ...

What is the best way to transform a series of character codes into a string using JavaScript?

Check out this interesting function I came across: function ungarble(garble){ var s = ""; for( var i = 0; i < garble.length; i++ ) { s += String.fromCharCode(garble[i]); } return s; } This function accepts an array of charCodes as input an ...

How many server queries does a single web application require?

As someone new to web app development, my main goal is to optimize speed as much as possible. I am faced with two options: The first option is to fetch data from the database individually every time a refresh is needed in the app. Alternatively, I c ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...

Challenge encountered when attempting to incorporate a heart icon into Bootstrap 5 Carousel

I'm facing an issue with the heart/favorites icon in the Bootstrap 5 carousel. How can I make it change from filled (red) to empty (white) when clicked? <div id="myCarousel" class="carousel slide" data-bs-ride="carousel&quo ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...

Protractor - Not waiting for all elements to load before opening a popup window

Despite my efforts to ensure the stability of my test, there are instances where it does not wait for all elements within an integrated popup, resulting in failure. This particular test case is quite intricate as it involves nested if statements to execut ...

JavaScript's inability to load images lazily poses a significant challenge

I'm having trouble implementing lazy loading for my images using JavaScript. When I change the html attribute from src to data-src, the images do not display at all. Additionally, when attempting to use an intersectionObserver to lazily load the image ...

Using getStaticProps in Next.js to retrieve menu data and seamlessly integrate it into the layout

I have integrated Sanity.io as a backend for my project, specifically managing the data for my main menu in parent/children object arrays. While I am able to successfully fetch this data, I prefer to utilize getStaticProps to ensure that my site remains c ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

Navigate to the following slide by clicking on BxSlider

Looking to enhance the navigation on my slideshow by using the slide itself as a next button, instead of relying on traditional prev/next controls. Although it seems like a simple feature to implement, I'm struggling to make it work. This is my curre ...

How can I use Node.js Express to upload files with Multer?

I am facing an issue while trying to upload a file image using multer in express. The file gets successfully uploaded to the directory, but the name of the file is not being saved in the database. I am utilizing mongodb with express and currently, the file ...

Server-side rendering or updating of React elements

One issue I am facing in my React app is that while all components can update themselves through the browser, a specific module called jenkins-api only functions when called server side. To retrieve the data and pass it into my template, I have utilized th ...

a guide on incorporating jQuery ajax requests with node.js

Although I came across a similar question on Stream data with Node.js, I felt the answers provided were not sufficient. My goal is to transfer data between a webpage and a node.js server using a jQuery ajax call (get, load, getJSON). When I try to do this ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

elasticsearch query for deletion only returns documents that are not found

I have been attempting to use the https://www.npmjs.com/package/elasticsearch-deletebyquery package to delete documents using a query. However, I keep receiving a "Not found" error. Here is my code snippet: client.deleteByQuery({ index: index, type: t ...

Transferring a CSV file to the server from a React application using multi-part form

In order to post a CSV file to an API using React, I have attempted to do so in multipart form. While many tutorials and websites suggest using the fetch() method for sending files to a server, I am encountering some challenges. The issue lies with my RES ...

Saving the data of a variable to a text file

I've developed a simple system to capture a person's First and Last name (this is the basic code, of course). But I'm interested in outputting the value of a variable to a text file. I've tried using some php, but it doesn't seem t ...

What could be the reason for the unsuccessful login attempt on Reddit using superagent in Node.js?

Here's a simplified test scenario that may be of some help. If you are more comfortable with using the native Node HTTP or the request library, feel free to modify accordingly. Currently, I am receiving unexpected jQuery data in response to the HTTP P ...