Transferring information from a modal popup to a controller

I am attempting to pass parameters from a Bootstrap modal popup to my controller using Javascript and Ajax. However, when I click the button, it does not seem to work on the controller. How can I successfully send these parameters?

Below is the HTML code for my modal:

<div class="modal fade" role="dialog" id="mymodal">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <button class="close" type="button" data-dismiss="modal">&times;</button>

            <label for="infoh" id="info" name="info"></label>
          <input type="hidden" id="infoh" name="infoh" value="" />
        </div> 
        <div class="modal-body">

                <div class="row">
                    <div class="col-md-3">
                        @Html.Label("Product : ")
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="input-sm"  id="product" name="product"/>
                    </div>
            </div><br />

            <div class="row">
                <div class="col-md-3">
                    @Html.Label("Price : ")
                </div>
                <div class="col-md-3">
                    <input type="number" class="input-sm" id="price" name="price"/>
                </div>
            </div>

        </div>
        <div class="modal-footer">
            <button class="btn btn-success" id="change"  onclick="func(this)"  name="change">@Html.Label("change") </button>
        </div>
    </div>
</div>

The modal functions correctly. Here is the Javascript code:

@section Scripts{
<script type="text/javascript">




  func(x) {
      var pricee = document.getElementById("price").value;
      var productt = document.getElementById("product").value;
      var info = document.getElementById("infoh").value;
      $.ajax({
          url: 'myController/Action',
          type: 'POST',
          data: { 'info': info, 'price': pricee, 'product': productt },
          success: function () {
              alert("done");
          }
      });

            }



</script>

}

and here is my Controller code, which does not seem to work or trigger:

  [HttpPost]
    public ActionResult Action(string info,double price,double product)

    {
        dbEntities updateaction = new dbEntities();
        int id = (Convert.ToInt32(Session["id"]));

        string myinfo = info;
       Product pp= updateaction.Product.Where(m => m.database_id.Equals(id) && m.name.Equals(myinfo)).SingleOrDefault();
        pp.price = price;
        pp.product = product;
        int i= updateaction.SaveChanges();
        Session["warning"] = i;
        return View();
    }

I am using the Opera Browser and I am unable to set a breakpoint in my code.

Answer №1

Ensure all input is enclosed within the form tag:

<form enctype="multipart/form-data">
<div class="modal fade" role="dialog" id="mymodal">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <button class="close" type="button" data-dismiss="modal">&times;</button>

            <label for="infoh" id="info" name="info"></label>
          <input type="hidden" id="infoh" name="infoh" value="" />
        </div> 
        <div class="modal-body">

                <div class="row">
                    <div class="col-md-3">
                        @Html.Label("Product : ")
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="input-sm"  id="product" name="product"/>
                    </div>
            </div><br />

            <div class="row">
                <div class="col-md-3">
                    @Html.Label("Price : ")
                </div>
                <div class="col-md-3">
                    <input type="number" class="input-sm" id="price" name="price"/>
                </div>
            </div>

        </div>
        <div class="modal-footer">
            <button class="btn btn-success" id="change"  onclick="func(this)"  name="change">@Html.Label("change") </button>
        </div>
    </div>
</div>
</form>

Include the following JavaScript code:

function func(x) {
    var pricee = document.getElementById("price").value;
    var productt = document.getElementById("product").value;
    var info = document.getElementById("infoh").value;
    $.ajax({
        url: '@Url.Content("~/myController/Action/")',
        type: 'POST',
        dataType: 'application/json',
        data: { 'info': info, 'price': pricee, 'product': productt },
         success: function (response) {
            alert(responseText.text);
        }
    });

}

Implement a JSON post method:

   [HttpPost]
    public JsonResult Action(string info, double price, double product)
    {
        db Entities updateaction = new dbEntities();
        int id = (Convert.ToInt32(Session["id"]));

        string myinfo = info;
        Product pp = updateaction.Product.Where(m => m.database_id.Equals(id) && m.name.Equals(myinfo)).SingleOrDefault();
        pp.price = price;
        pp.product = product;
        int i = updateaction.SaveChanges();
        Session["warning"] = i;
        return Json(new { success = true, responseText = " Sucessfully." }, JsonRequestBehavior.AllowGet);
    }

Answer №2

There are multiple issues present in the JavaScript function provided, so here is the corrected version:

function updateProductInfo(x) {
        var price = document.getElementById("priceInput").value;
        var productName = document.getElementById("productNameInput").value;
        var productInfo = document.getElementById("productInfoTextarea").value;
        $.ajax({
            url: '@Url.Content("~/myController/Action/")',
            type: 'POST',
            dataType: 'json',
            data: { 'info': productInfo, 'price': price, 'product': productName },
            success: function () {
                alert("Update successful");
            }
        });

    }

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

Manipulating element height in AngularJS

My goal is to utilize the bootstrap style for a fixed navigation bar at the top of the page. By using navbar-fixed-top, I can fix an element to the top. The visibility of #subnav will be determined by the value of showsubnav. <div id="backnav"> ...

Creating a Python web scraper that utilizes Selenium and PhantomJS to extract DOM information

Attempting to extract data from a website that uses JavaScript to build the DOM, I employed both Selenium and PhantomJS. While the code provided below sometimes works, it often retrieves an empty website without executing the necessary JavaScript. Only oc ...

What strategies can I use to make my div content more adaptable to different screen sizes and

Currently, in my project, I have implemented a layout using the top nav menu (purple part) and the left menu (pink part) as shown in the image. However, I am facing an issue where, upon deleting some content from the view, the pink menu on the left extends ...

Warning: Using synchronous XMLHttpRequest on the main thread is no longer recommended as it can negatively impact the user's experience

I encountered an issue with my project while attempting an Ajax request [Warning] Using synchronous XMLHttpRequest on the main thread is now considered deprecated due to its negative impact on user experience. function retrieveReviews() { var reviewsD ...

Oops! Looks like there was an issue: TypeError - 'app.use() function needs a middleware'

Recently delving into Node Js, I embarked on a learning journey and attempted the following code. However, it seems to be throwing an error that has left me stumped. Despite searching for solutions, I can't seem to pinpoint what's causing the iss ...

A single Ajax call exhibiting varied behavior within a .NET framework application

I have encountered an issue with a webform that contains an ajax call. Surprisingly, the ajax call works perfectly fine on a standalone project, but when I integrate the same code into an existing project, it causes the page to refresh. The existing projec ...

When you duplicate the React State object and make changes to the copied object, it directly affects

When attempting to duplicate a state object, I noticed that the state object is being modified directly in the code snippet below: @boundMethod private _onClickDeleteAttachment(attachmentName: string): void { console.log("_onClickDeleteAttachment | th ...

Looking to empty a textbox, give it focus, and avoid triggering an ASP.NET postback all with a single click of a

I am working on an ASP.NET project and I have a simple HTML button. When this button is clicked, my goal is to clear textbox1, set the focus on textbox1, and prevent any postback from occurring. However, I am running into an issue where preventing postba ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Refresh HTML table when database is updated

My panel has a user table which is populated using the following snippet of Php code : <html> <body> <div id="order_table"> <table> <thead> <tr> <th>Name</th> < ...

Using my chat platform with PHP and AJAX is causing my browser to become unresponsive

This particular script is my go-to for a variety of tasks such as scrolling, retrieving data from PHP, and more: <script> $(document).ready(function(){ $("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500); ...

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

What is the process for retrieving a group of objects from a session in code?

Currently, I am working on creating an invoice system. For registered users, the invoices and their units are saved to the database (where one invoice can have multiple units). On the other hand, for users who are not logged in, I am attempting to store th ...

The CORS header 'Access-Control-Allow-Origin' is nowhere to be found

When I try to call this function from my asp.net form, I encounter the following error in the Firebug console while attempting to make an ajax request: Cross-Origin Request Blocked: The Same Origin Policy prevents me from accessing the remote resource lo ...

Tips for maintaining the full width/height ratio of a child image when covering a fixed size container

I have a square container with dimensions of 300x300 and an <img src="" /> image inside. My goal is for the image to cover the entire container while maintaining its width/height ratio. If the image's width is smaller than its height ...