Show information on the following screen by utilizing ajax when the button is pressed

I need to implement functionality on my cshtml page, ListZoneRecords.cshtml, where clicking on a zone row should display its details on another page. I am looking to achieve this using ajax.

//ListZoneRecords.cshtml
<script>
$('#btn_sbmt_details').click(function () {
            var id = $('#i_zone_id').val();
            $.ajax({
                url: "/ZoneModels/GetByKey",
                data: { id: id},
                type: "GET",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
            })
        });
 </script>

Upon pressing the button btn_sbmt_details, it triggers the GetByKey method in the controller, which searches for the specified id and retrieves the details. The challenge now is to display these details on a different cshtml page such as ZoneDetails.cshtml. Can this be done through ajax?

The corresponding controller method:

public JsonResult GetByKey(int? id)  
    {   var data = (from z in db.ZoneModels 
                where z.ZoneId == id
                select z).ToList();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Alternatively, do I need to use proper MVC practices by creating a view page for the GetByKey method and then executing return View(data);?

public ActionResult GetByKey(int? id)  
    {   var data = (from z in db.ZoneModels 
                where z.ZoneId == id
                select z).ToList();
        return View(data);
    }

Answer №1

Set up an action in your controller for ZoneDetails.cshtml (assuming it is located in ZoneModelsController.cs). Next, go to that action and pass the id through a query string. This will generate a URL like /ZoneModels/ZoneDetails?id=1

Here's a sample template:

ListZoneRecords.cshtml

<script>
$('#btn_sbmt_details').click(function () {
    var id = $('#i_zone_id').val();
    window.location = "/ZoneModels/ZoneDetails?id=" + id;
});
</script>

ZoneModelsController.cs

public ActionResult ZoneDetails(int? id)  
{
    List<Object> detailsListy = GetByKey(id);
    
    // add code here to set up view model
    
    return View(model); 
}

public List<Object>  GetByKey(int? id)  
{   
    var data = (from z in db.ZoneModels 
                where z.ZoneId == id
                select z).ToList();
    return data;
}

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

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

jquery code to show/hide all elements

My webpage contains multiple content tabs with expand/collapse icons in each panel. To simplify the process of closing all expanded sections, I have included buttons for expanding and collapsing all panels at once. While this feature is functioning correc ...

The functionality of .bind() is malfunctioning on both Microsoft Edge and Google Chrome browsers

Everything seems to be running smoothly on Mozilla (version 103.0), but unfortunately, it's not performing as expected on Chrome or Microsoft Edge. $('#loading').bind('ajaxStart', function () { $(this).show(); }).bind('ajaxS ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

The value of $.data is not defined

Below is the HTML code snippet from my MVC razor view: <div style="visibility:visible;"> var info = [ {"id":"1", "bg_color":"Green", "text_color": "Black"}, {"id":"2", "bg_color":"Amber", "text_color": "Black"}, {"id":"3", "b ...

Node.js encounter an error while processing an Ajax request

Running a node.js server on port 3000, my index.html file sends an Ajax request to a apache2 server on port 80 in order to retrieve the current cookie on the site. Despite seeing the cookie on the browser, no cookie response is received. The Ajax request i ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...

Utilizing jQuery to append a function to an object and subsequently initiate an event on it

In the scenario presented, I have a jQuery Object called $wrapper = $(this);. This occurs within an init call as shown here: $('#unique-wrapper-id').initWrapper()'. The initWrapper() function is part of jQuery.fn. Within the initWrapper() c ...

Leveraging AJAX in Ruby on Rails

In my controller, I have a function that looks like this: def showRecipeIngredients ingredients = RecipeIngredient.where( "recipe_id = ?", params[:id]).all @html = "" ingredients.each do |i| @html = @html + "<p>#{Food.find_by_ndb ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

modifying the href attribute of a tag is determined by the value of window

I'm working on a jQuery snippet that detects the current window's URL and, depending on the href value of the window, changes the href of an anchor tag. Here's what my code looks like so far: (function($) { "use strict"; $(document).re ...

Executing a Particular Function in PHP with Arguments

As a newcomer to PHP and JavaScript, I'm attempting to invoke a specific function in a PHP file from JavaScript. Here is my code: <script> function load($dID) { $.ajax({ url: "myPHP.php", ...

How to use JQuery to retrieve multiple background image URLs from CSS styling

Initially, here is the CSS code that I am working with: background-image: url(/style_elements/img/first.png), url(/style_elements/img/second.png); I am trying to specifically target the second background image URL using jQuery: var item_img_url = item_i ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

The CSS :first-child selector appears to be malfunctioning with the majority of elements

Having some difficulty with the :first-child selector. It just won't cooperate in my code. The goal is to execute a simple transform on two elements using the :first-child, but it's failing in multiple instances. Let me explain: First scenario: ...

I attempted to retrieve data using the post method with Scrapy, but unfortunately received a

After examining the request using F12 in Chrome and Postman, I found detailed information on the site. (email:[email protected], password:wsc111111), and proceeded to The goal was to collect all the columns followed by user Hynuza, which currently s ...