Moving data from an MVC table row to a Bootstrap modal popup

Currently, I am utilizing the bootstrap-table library to generate a table within my ASP.net MVC view. The requirement is that when a user double-clicks on a table row, the data from that specific row should be transferred to a modal popup model.

I have successfully managed to retrieve the column values of the row using the row[] array in JavaScript. However, I am facing difficulty transferring this data to my controller via Ajax.

Below is an excerpt of my code:

<html lang="en-AU">
<head>
<script>

$(document).ready(function () {

$('#tblID').bootstrapTable({ locale: 'en-US' }).on('click-row.bs.table', function (e, row, $element) {

var param = row[2]; //retrieving value from the 3rd column

$.ajax({
      type: "GET",
      url: '@Url.Action("_SampleAction", "SampleController")',
      data: '{ID: "' + param + '" }',
      datatype: "json",
      success: function (result) {
      $('#myModelContent').html(result);
      $("#myModal").modal('show');
      },
      error: function (req, status, error) {
           alert("Error occurred");
      }
    });

});

});

</script>
</head>

...

Upon executing the above code snippet, the parameter ID is being received as null and the Ajax call is failing.

If anyone can provide guidance on how to resolve this issue, it would be greatly appreciated. Thank you in advance.

Answer №1

When using AJAX callback, it's important to note that redirection to another action method should not be done (avoid assigning the data parameter with string concatenation like data: '{ID: "' + param + '" }'). Instead, configure the AJAX callback to check for error messages before taking any actions:

$.ajax({
      type: "GET",
      url: '@Url.Action("_SampleAction", "SampleController")',
      data: { ID: param }, // pass strings properly to controller using AJAX

      // other AJAX settings

      success: function (result) {
          if (result.message == undefined) {
              $('#myModelContent').html(result);
              $("#myModal").modal('show');
          } else {
              // handle redirection here instead of using RedirectToAction from the controller
              window.location.href = result.url;
          }
      },
      error: function (req, status, error) {
           alert("An error occurred");
      }
    });
});

Additionally, the controller action should return JSON data in case of an exception, as shown below:

public ActionResult _SampleAction(string ID)
{
    MyModel objMyModel = new MyModel();
    objMyModel.ID = ID;
    try
    {
        // perform necessary actions

        return PartialView("_SampleAction", objMyModel);
    }
    catch (Exception ex)
    {
        return Json(new { url = Url.Action("Index", "Error"), message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}

For a related issue, refer to this question on Stack Overflow:

RedirectToAction not working after successful jQuery AJAX post?

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

I need to extract particular information from a JSON file and include it in another JSON file or variable

Hey there, I'm looking to retrieve specific data from an API and store it in a file. The API I am interested in is quite large, so I only want to extract certain information for each item, such as the 7-day price. However, when I attempt to use an emp ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

What are some ways to keep text within the boundaries of a div element?

I have tried multiple solutions for this issue, but none seem to be working for me. When I append a paragraph to a div, the text extends beyond the element. Below is the code I am using. Any assistance would be greatly appreciated. CSS: .chat-h { margi ...

How can I send a form without having the page reload using a combination of AJAX, PHP

I am struggling to submit a form without refreshing the page. I have tried using ajax as mentioned in some resources, but it's not working for me. What could be the issue? When I use the following code, everything works fine with PHP: document.getEl ...

Troubles with IE7 regarding jQuery [clicking and changing events]

My code snippets are designed to loop through cached JSON data on the 1st click function and display any values that exist for a specific id. The 2nd change function captures when elements' values change (e.g., from yes to no). Since these elements a ...

Is there a way to convert my function into a variable in order to execute an array of statements

I'm struggling to convert this code into a variable. I need to bind it inside a statement execute array. This is the code I am working on, which retrieves the current date and timezone. I attempted using $date = function() {}, echo $date(); but that ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

Alert: Every child within a list must be assigned a distinct "key" property in React.js

After reading the article on looping inside React JSX, I decided to enhance my code by rendering components through a loop. However, an issue has arisen in the form of a warning message: Warning Each child in a list should have a unique "key" pro ...

Issue with storing callback in parent component state leading to a stale closure situation

I've encountered a situation where I need to register a function in the state of my parent component. This function captures some local state within the child component. However, there is an issue where the function always retrieves an outdated value ...

Manipulate database variables using Javascript

As a beginner in JavaScript, I am seeking assistance with some tasks. I have to save a simple number as a JavaScript variable into a database and display the current value on two websites (with PHP used to retrieve it on the second site). This is my curre ...

css: varying container heights for columns in Chrome and Safari using Bootstrap 4

In my code snippet below (this is just a prototype, in the actual application everything is different but follows a similar structure): <body> <div class="row"> <div class="col-3 d-none d-sm-block"> <div class="h-1 ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Using an array of objects with useState

I have a search box where I can paste a column from Excel. Upon input, I parse the data and create an array of entries. Next, I loop through each entry and utilize a custom hook to retrieve information from my graphql endpoint. For instance: If 3 entrie ...

The final picture exceeding the boundaries in the Bootstrap photo album

After taking inspiration from the bootstrap album, I decided to create my own album. I encountered a problem where the last image in each row appears larger than the first two. I have examined the css code but have been unable to pinpoint the issue. You ...

Sorting tables by various headings based on the information in each column - Addressing a previous question about table organization

This was a question that was previously asked: How can I implement CSS table sorting based on different headings in the table? and this was the accepted solution: $("#<ID_OF_YOUR_TABLE").dataTable(); Here is a working fiddle with the solution: http ...

Unable to retrieve JSON data in the console

Having trouble logging the data before displaying it on the page; I keep encountering a 404 error or an attribute error 'Profile' does not have a username attribute. I am new to working with JSON and have only recently started experimenting with ...

Organize information before making a choice in the dropdown menu

Currently, I have a dropdown menu in HTML that allows you to order the data by different options: <select ng-model="sortOrder" ng-options="option.value as option.name for item in options"></select> In addition, I have implemented code using n ...

Guide to deploying an ExpressJS application using Namecheap's cPanel

I am facing a challenge in deploying my website, built with ExpressJS, on namecheap's cPanel using cloudflare. The issue arises because there is no direct option to host a Node.js application, leading me to resort to utilizing the cPanel's termin ...

Utilizing Json.NET for the process of serialization

When utilizing JavaScriptSerializer, the serialization process looks like this: var serializer = new JavaScriptSerializer(); string requestData = serializer.Serialize(new { EventID = 1, SubscriberID = 5, ToList = "abcd", TemplateParamVals = " ...

I am interested in updating the default Bootstrap Hamburger icon

I'm trying to customize the default Bootstrap Hamburger Icon, but I'm struggling to figure it out. Can someone help me with this? <button class="navbar-toggler" type="button" data-toggle="collapse" data-target= ...