Utilize Ajax.ActionLink on a DIV by incorporating data from the Model

Although there are similar questions on this topic already, they do not address the specific issue of using values from the model as arguments for the controller.

Make DIV containing AJAX ActionLink clickable

Div as Ajax.ActionLink

Take a look at the following code in a Razor view:

@foreach (var item in Model)
{
    <div class="itemDisplay">
        <img src="~/Images/@item.DisplayImage" />
        @Ajax.ActionLink($"Item {item.Id}", "_ItemDisplay", new { id = item.Id }, new AjaxOptions { UpdateTargetId = "itemDisplay", LoadingElementId = "ajax-loader", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }, null)
    </div>
}

The goal here is to apply the ActionLink to the entire DIV.

The challenge arises when attempting to use JavaScript variables within Razor code due to the client-side and server-side distinction.

For example:

function updateItemDisplay(itemId) {
    $('#itemDisplay')
        .click(function () {
            $.ajax({
                url: '@Url.Action("_ItemDisplay", new { id = *cannot use a JS variable here!* })',
                type: "GET",
                success: function (result) {
                    $('#itemDisplay').html(result);
                }
            });
        });
};

So my query is, with ASP.Net MVC, how can I initiate an AJAX call from a DIV tag and pass the relevant ID to the controller?

Answer №1

One straightforward resolution was to construct the URL by combining the variable with the string produced by Url.Action:

'@Url.Action("_ItemDisplay")' + '/' + myVar

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

Showing dummy data in demo mode with an AngularJS table

I stumbled upon this interesting jsfiddle http://jsfiddle.net/EnY74/20/ that seems to be using some demo data. If you check out this example https://jsfiddle.net/vsfsugkg/2/, you'll notice that the table originally has only one row, but I modified it ...

The process of uploading a file is interrupted by an AJAX Timeout

My HTML form includes a file input field that utilizes AJAX to upload the selected file, complete with a progress bar. However, I encountered an issue where the request would hang without any response. To prevent this from happening in the future, I aim t ...

The issue of "400 Bad Request Error" in Wordpress's admin-ajax.php file is

I am attempting to send data from a form using AJAX. Initially, I have a button labeled "add file". When this button is clicked, the form is displayed via AJAX and it functions correctly. However, upon submitting the form, I encounter a bad request error ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

Exploring the blur() function in JavaScript through cold calling

There is a specific line of code that I need help with. document.getElementById("firstName").addEventListener("blur", validateField); Additionally, there is this block of code: validateField = (event) => { const el = event.targe ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

What could be causing Django REST Framework to block non-GET requests with a 403 Forbidden error from all devices except for mine?

Currently in the process of developing a web app using a Django REST Framework API. It runs smoothly on the computer where it was created (hosted online, not locally), but when trying to access the website from another computer, all GET requests work fine ...

Is there a way to ensure seamless animation when dynamically adding components in react native?

I am working on a React Native application where I have implemented a card with a conditional <Text> component. This text is rendered when a button is pressed and removed when the same button is triggered again. Below is a snippet of my code: <V ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...

Unleashing the power of jQuery ajax without requiring a server

I've been incorporating jQuery ajax calls on my HTML pages. $.ajax({ url: 'search/' + page + '.html', dataType: 'text', success: function(data) { $(".searchData").html(data); $(".searchData"). ...

Tips for automatically setting focus to the following cell after inserting a new row in AngularJS

Transitioning from the Knockout world to Angular, I am facing an issue with a key-press event for tab. Whenever I add a new row in the table, the focus shifts to the information icon in the URI bar instead of the next cell in the newly created row. I belie ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...

Delay the execution in selenium webdriver using Java until the login button is clicked manually

Can Selenium Webdriver be used to pause code execution with webdriver.wait until the user clicks the login button on a form? The form includes a Captcha that requires manual input, preventing automated clicking of the button by the script. Clicking the log ...

Creating with NodeJS

I'm encountering an issue where my code is not waiting for a response when trying to retrieve data from a database. The connection is fine and everything works well, but Express isn't patient enough for the data to come through. Despite trying v ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

The error message "bind is not defined in chat.js on line 89 in React js" appears due to a ReferenceError

Greetings! I am new to working with React JS and have encountered an error in my code while developing a project. The console shows the following message: chat.js:89 Uncaught ReferenceError: bind is not defined(…) I am struggling to identify where I ...

retrieve today's date with parsed time using moment

I am attempting to retrieve the current date and time, with the specified time using moment js. Here's what I have tried. const time = '18:00' const timeAndDate = moment(time) However, when I display timeAndDate, it indicates an invalid da ...