Discovering the clicked button in a partial view during an onSuccess Ajax call

Within my partial view, I have implemented two buttons: Save and Preview. Both buttons are functioning as expected, with Preview enabling widget preview and Save saving data to the database. However, I am encountering two issues:

  1. I am unable to determine which button was clicked (within the onSuccess of Ajax.BeginForm).
  2. The controller is not redirecting to the specified action link.

Here is a snippet of my controller code:

public ActionResult EditWidget(WidgetViewModel viewmodel, string onSave, string onPreview)
{
    if(!string.IsNullOrEmpty(onPreview))
    {
        // Code for handling Preview button click
    }
    else if(!string.IsNullOrEmpty(onSave))
    {
        // Code for handling Save button click
    }

    return null;
}

Below is my partial view:

@using (Ajax.BeginForm("EditWidget", "Home", new AjaxOptions { UpdateTargetId = "divPreview", HttpMethod = "POST", OnSuccess = "application.getpage.onSuccessPreview" }))
{
    <!-- Form content here -->
}

And the onSuccess function:

onSuccessPreview: function (data, textStatus, jqXHR) {
// Need to identify which button was clicked in the partial view  and handle redirection accordingly
}

Answer №1

To enhance functionality, consider including a hidden input field:

<div class="form-inline">
    <input id="btnSave" name="onSave" type="submit" class="btn btn-primary" style="width:65px" value="Save" />
    <input id="btnPreview" name="onPreview" type="submit" class="btn btn-primary" style="width:65px" value="Preview" />
    <input type="hidden" id="clicked-button" />
        </div>

Update the hidden input's value using an onclick event in JavaScript (prior to submission) and retrieve it in your success function:

onSuccessPreview: function (data, textStatus, jqXHR) {
     var pendingClick = $("#clicked-button").val();
    }

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

JS: Discovering an element's screen position consistently across various computers

I am currently working with a matrix of size 13 x 20, where each cell contains a number ranging from 0 to 300, representing different tiles to build a map. In addition, there is a "hero" character - a movable image. Pressing an arrow key will move the her ...

How to use jQuery to iterate through a C# serialized List<string>

I am working on a webmethod that reads the first line of a CSV file to extract the column titles and then stores each item in a list to be returned to an ajax call. Below is the code snippet for this functionality: [WebMethod] public static string getAvai ...

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Using Jquery and the cookie.split method to extract and eliminate a value from a cookie

I am trying to figure out how to remove a specific matching value from a cookie using JavaScript. I have written a script that loops over the cookie and checks for matches, but I can't seem to successfully remove just the matching value. Any tips on a ...

Showing formatted JSON in the view using ASP.NET MVC

Is there a method to modify JSON for presentation in the interface? I am looking for a way to automatically update my API documentation when adding new properties. It would be great if I could also apply CSS styling to certain elements. This feature is som ...

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

The NSException thrown by the TableView

Just diving into Swift and trying to parse JSON using ObjectMapper for displaying data in a TableView, but encountering an issue: libc++abi.dylib: terminating with uncaught exception of type NSException The error occurs after the method numberOfRowsInS ...

In making reference to a particular subpage within a parent page

My website is designed with all inner pages linked to one master file. I'm looking to change the title font size on just one specific page, without affecting the rest of the pages that use the master file. Is there a way to target a specific page titl ...

Dynamically extract key values from JSON data and display them on an HTML page with checkboxes for selection. Generate a new JSON object containing

I am facing the challenge of parsing an unknown JSON with uncertain key-value pairs. As I do not have prior knowledge of the keys to access, my goal is to traverse through every key in the JSON and display all keys and their corresponding values on the scr ...

What is the process for reading and parsing a JSON byteCode file?

After creating a JSON file and saving it as a text file in my hard drive using FileOutputStream, I then proceeded to read the file in a separate class using FileInputStream. The code snippet below is used to print the JSON data, but now I am wondering ho ...

The dual roles of Rust in managing JSON serialization duties

Exploring the realm of Json serialization in Rust has been quite enlightening. In particular, I am currently focused on how to efficiently serialize Rust objects into Json format. After delving into this topic, I have identified three distinct methods for ...

Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a ch ...

Ag-grid: how to reset a cell when using the "agSelectCellEditor"

According to the documentation on ag-grid: If Backspace or Delete is pressed, the default editor will clear the contents of the cell. However, this behavior does not apply when using the "agSelectCellEditor." Pressing Delete or Backspace puts the cell i ...

JSON arrays that are nested within one another

I am currently working on parsing some JSON data that contains nested arrays, and I'm facing difficulties extracting the data from the inner arrays within the main array. This is a snippet of how my JSON data is structured: {"TrackingInformationResp ...

Generate a new style element, establish various classes, and append a class to the element

Is there a more efficient solution available? $("<style>") .attr("type", "text/css") .prependTo("head") .append(".bor {border:2px dotted red} .gto {padding:10px; font-size:medium}"); $("input:text").addClass("bor gto").val("Enter your t ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

How can you identify when a Vuetify radio button is re-selected?

Currently, I am developing a wizard that involves triggering navigation when a radio button is selected. Users should also be able to go back and change their previous choices. However, one issue I have encountered is the difficulty in detecting a re-selec ...

Bootstrap tab content getting shifted downwards

Having an issue with the Tab plugin in Bootstrap on a particular page. The tab body is being pushed down 400px below the actual tabs. This behavior is only occurring on this specific page, while most other pages using the same plugin are functioning fine. ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Transform the JSON data into a PHP string

Looking to extract the "distance" value of "3.0 mi" from the Google Maps API response and convert it into a PHP variable. Here is an example link: https://maps.googleapis.com/maps/api/distancematrix/json?origins=TN222AF&destinations=tn225dj&mode=b ...