Using Ajax.ActionLink to pass a parameter in JavaScript

When I call a controller in this manner:

@Ajax.ActionLink("Clients", "ClientAccountsPartialView",
                      new {
                          entityCode = -1,
                          taxNumber = -1,
                          country = 1,
                          district = 1,
                          council = -1
                      },
                      new AjaxOptions {
                          InsertionMode = InsertionMode.Replace,
                          UpdateTargetId = "SearchClientsID",
                          HttpMethod = "GET",
                          OnBegin = "onBegin",
                          OnComplete = "onComplete"
                      },
                      new
                      {
                          @class = "btn btn-default",
                          @onclick = "$('#SearchEntitiesModal').modal('hide'); $('#SearchClientsModal').modal('show')",
                          @style = "width:100%;", 
                          @id="searchClientsButton"
                      })

However, I am in need of passing a JavaScript parameter. Does anyone have a solution for this?

Answer №1

Here is an example of how to achieve the functionality without using the @Ajax.Actionlink; by using JQuery:

Button:

<button class="btn blue" id="btnEditAddressConfirm">
    Save
</button>

JQuery:

$('#btnEditAddressConfirm').on('click', function () {

    var employeeId = $('#hiddenEmployeeId').val();
    var newAddressLine1 = $('#tbNewAddressLine1').val();
    var newAddressLine2 = $('#tbNewAddressLine2').val();
    var newAddressTown = $('#tbNewAddressTown').val();
    var newAddressCounty = $('#tbNewAddressCounty').val();
    var newAddressPostcode = $('#tbNewAddressPostcode').val();

    //You can also retrieve parameters from other parts of your javascript here....

    $.ajax({
        url: '@Url.Action("EditEmployeeAddress", "Employee")',
        type: 'GET',
        dataType: 'json', //only required for returned data
        cache: false, //set cache to false to prevent browser caching of GET requests
        data: {
            employeeId: employeeId,
            newAddressLine1: newAddressLine1,
            newAddressLine2: newAddressLine2,
            newAddressTown: newAddressTown,
            newAddressCounty: newAddressCounty,
            newAddressPostcode: newAddressPostcode
        },
        success: function (data) {
            if (data === true) {
                //Perform actions based on success
            }
            else {
                alert("Error occurred!!!");
            }
        }
    });
});

Controller Action:

public string EditEmployeeAddress(
    int employeeId,
    string newAddressLine1,
    string newAddressLine2,
    string newAddressTown,
    string newAddressCounty,
    string newAddressPostcode)
{
    //Implement desired functionality here...
}

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

Error encountered in Selenium Webdriver: A duplicate key has been detected and added to the collection

Looking for advice on how to avoid the error message: "An item with the same key has already been added." Can anyone help? I have two tests that pass individually, but when I run them all at once in Visual Studio, I encounter this error. [Binding] public ...

What is the best way to include a dialog div within a form tag?

I am facing an issue with a JQuery dialog on my webpage. The data entered into the dialog seems to get lost because the dialog is placed outside the form tag. Here is how it appears: https://i.stack.imgur.com/fnb07.png So far, I have attempted this soluti ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...

Regular expression: Validate in PHP (on the server-side) or JavaScript (on the client-side)

I am working on a form that validates user input using PHP, JavaScript, and AJAX. I plan to use regex to validate each field, but I'm unsure about which method is best for checking it... In your experience, do you recommend using JavaScript or PHP fo ...

Guarantee of SQL integration within JavaScript

I am trying to retrieve the value of the message variable, but all I see in the console is the following: result [object Promise] async function Testing() { let response = await new Promise((resolve, reject) => { db.query("SELECT * FROM `ni ...

React virtual list module: Scrolling down through code commands

In my React Grid with Virtual Scrolling, I am facing a challenge with the lack of a "scroll to row feature." At times, I need to select a specific row programmatically and ensure that it is displayed to the user. Although I have the ID of the desired row ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

How to convert table headings in Bootstrap-Vue.js

For a few nights now, I've been struggling to translate the table header in my vue.js component. It seems like I'm missing something as I'm new to Vue.js and can't seem to figure out what's wrong. Translating within the HTML works ...

Developing a visual representation of network utilization using ASP.NET

I need assistance in developing a timeline chart to showcase the network usage history of my company. The DBA has assured me that the necessary data exists and will be providing a query to extract that information from the database for me to work with. As ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

What is the best way to turn off default CSS styling in KendoUI?

I am facing an issue in my application where I am using global CSS definitions for "INPUT", "SELECT", and other elements. The problem arises when I try to incorporate KendoUI widgets, as they override my default CSS styles. For instance, my CSS code looks ...

Calling Array.prototype.slice results in an array with no elements

As a beginner in Javascript, I am looking to save JSON request data to a sub document in a MongoDB database. My current approach involves converting the JSON request into an array and then utilizing the $push method to pass the array to the sub document. H ...

What is the best way to create 2 select boxes that will disable each other if they match, and then automatically choose the second option so they do not match

Is there a way to have 2 select boxes automatically change one option to the second option on one box when they match? Instead of using an "alert", I am looking for a function that can automatically update one option in one of the select boxes if they mat ...

jQuery can't capture form submission

I've been trying to implement this seemingly simple piece of code, but no matter what I do, it just won't work. I've followed several examples online and even tested it on both IE and Chrome without success. One thing that did work was testi ...

import a function from jQuery that has been defined in an external JavaScript file

Whenever I attempt to execute this action, I encounter an error stating that the function is undefined $(function () { function Example(){ Example1(); } Example1(); }); external.js $(function () { function Example1(){ alert("Hello"); } }); ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

Updating the content within the main body of the page rather than the sidebar in react-router v5

I have a question regarding the functioning of my sidebar and content. So, when I click on any item in the sidebar, the content changes accordingly. But what if I want to change the route directly from the content itself? That's where I'm facing ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...