Sending DataView to controller using JavaScript

Struggling to establish communication between the view and controller for updating values in the database using JavaScript, MVC, and Asp.Net. Here is a snippet of my view:

function updateRejectType() {
   $("#btnvalider").click(function () {
    var IdRTDoc = <%: ViewData["IdRTDoc"] %>;
    var strDocumentType=<%: ViewData["RejectedTypesList"]  %>;
    var strLabel= <%: ViewData["strLabel"] %>;

$.ajax({
         type: "GET",
         url: '<%= Url.Action("UpdateRejectedType", "RejectedTypes") %>',
         data: "IdRTDoc=" + IdRTDoc +"DocumentType"+ strDocumentType + "Label" + strLabel,
         processData: false,
         cache: false,
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         complete: function () {
        alert("updated");
                               },
         success: function (result, request) {
             alert("Mis à jour avec succès");
             SuccessValider();
         },
         error: FailureFunction,
         failure: FailureFunctionUpdate
     });

});

}

function SuccessValider(){
window.open('../Home/About', '_parent');
}

function FailureFunctionUpdate() {
 alert("Problème survenu dans update !");
}


`
which contains the function

updateRejectType() that I call here

<input type="button" class="lien_bloc_gris" onclick="updateRejectType()" value="valider" name="btnvalider"><span> </span></a></input>

And here is my controller method

public virtual ActionResult UpdateRejectedType(int IdRTDoc, int strDocumentType, string strLabel)
{
    try {

        RejectedTypesViewModel obj = new RejectedTypesViewModel();
        obj.DocumentType = strDocumentType;
        obj.Label = strLabel;

        var result = repository.RejectedTypesUpdate("All", obj);
        return null;
    } catch (Exception ex) {

        return RedirectToAction("Error", "Shared");
    }
} 

Clicking on the button does not seem to trigger any action. What steps can be taken to resolve this issue?

Answer №1

Attempt to use the following code snippet for passing your information:

payload: {documentId: IdRTDoc, docType: strTypeDocument, title: strLabel},

Answer №2

Given that your button includes the onclick="updateRejectType()" attribute, there is no need to attach the click event using

$("#btnvalider").click(function ()
. Additionally, make sure to include & and = in the data option. Revise your script as shown below:

<script type="text/javascript>
    function updateRejectType() {
        var IdRTDoc = <%: ViewData["IdRTDoc"] %>;
        var strTypeDocument =<%:ViewData["RejectedTypesList"]  %>;
        var strLabel = <%: ViewData["strLabel"] %>;

        $.ajax({
             type: "GET",
             url: '<%= Url.Action("UpdateRejectedType", "RejectedTypes") %>',
             data: "IdRTDoc=" + IdRTDoc + "&DocumentType=" + strTypeDocument + "&Label=" + strLabel,
             processData: false,
             cache: false,
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             complete: function () {
                 alert("updated");
             },
             success: function (result, request) {
                 alert("Mis à jour avec succès");
                 SuccessValider();
             },
             error: FailureFunctionUpdate
        });
    }

    function SuccessValider(){
        window.open('../Home/About', '_parent');
    }

    function FailureFunctionUpdate(){
        alert("Problème survenu dans update !");
    }
</script>

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

The $.ajax() method is unable to fulfill a request for retrieving JSON data from a static JSON file

Having difficulty fetching JSON data from a static .json file located on an xampp server. I've successfully used getJSON for this task, but encountering issues with $.ajax(). Any assistance in identifying the error would be greatly appreciated. $.aj ...

Automating the process of populating preferredCountries from intl-tel-input with database output

I am looking to dynamically populate the preferredCountries:["xx","yy","zz"] array with a function that retrieves the most frequently used country codes from a MySQL database, listing them in descending order of usage and including those with a count of at ...

Is it possible to create an AngularJS and jQuery Calendar Directive that activates by clicking on a Bootstrap glyphicon?

I have successfully created a directive for my calendar using AngularJS and jQuery. The datepicker pops up when the user selects the input box. Now, I am attempting to allow the user to click on Bootstrap's 'glyphicon glyphicon-calendar' to ...

Developing a form using ASP.NET with dual models

I am currently using Visual Studio 2017 with all the latest updates installed. I am facing a challenge where I need to create a form with text box answer questions and a checkbox answer question, and then store all the answers in a single database entry. M ...

Unable to authenticate through LinkedIn

On my website, I am attempting to retrieve the user's first name, last name, and email using LinkedIn. Here is what I have done so far: In my LinkedIn App settings, under the Default Scope (OAuth User Agreement), I have selected the following options ...

Create a unique HTML id dynamically using AngularJS

Hello, I am looking to create a unique identifier in html in the format 'a1', 'a2', etc. based on the values in the table. I am thinking of achieving this in the following way: <div ng-controller="ddController" > ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

Leveraging the power of ES6 capabilities within the Express.js framework of Node

Recently, I've been experimenting with utilizing ES6 features in Express. Interestingly, I discovered that Nodejs now has built-in support for es6, eliminating the need for babel to transpile my code. Here's a snippet from my app.js file: &apos ...

What is the best way to search a map object that serves as the document ID in Firebase?

I am attempting to retrieve all fieldnames within the payload > (random doc id) objects. https://i.sstatic.net/y9703.png At this moment, my approach involves fetching other collections using the following code: async fetchPage() { const query = fir ...

Error: Although precheck is successful, the Chrome API Runtime has exceeded the QUOTA_BYTES_PER_ITEM quota

I keep receiving a QUOTA_BYTES_PER_ITEM error when attempting to store an object, even though my size precheck shows that it should be under the quota. I must be missing something simple here (is this method correct for checking object size?). I've al ...

Sending List<T> as query parameter

I am currently dealing with a list containing the names of different countries. I need to pass this list as a parameter in Response.Redirect(page). Is there an easy way to achieve this so that on the receiving page, I can simply typecast the query string i ...

Deactivate all functions of a complete row in the table

I'm working with a table that contains various user interaction controls in its cells, such as buttons and links. I'm looking to gray out certain rows of the table so that all operations related to those rows are disabled. Does anyone have sugge ...

Selenium allows the liberation of a webpage from suspension

I'm facing an issue with resolving the suspension of a website as shown in the image below. My goal is to access a ticket selling website every 0.1 seconds, but if it's busy, I want it to wait for 10 seconds before trying again. Visit http://bu ...

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

Facing difficulty transferring an array from React to Django

Trying to transfer an array from the React frontend (stored in local storage) to my view class in Django is resulting in the following error: Console Output: GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error) Django Logs: for qu ...

Keep the division visible once the form has been successfully submitted

Initially, I have created 3 divs that are controlled using input type buttons. These buttons serve the purpose of displaying and hiding the hidden divs. Within these divs, there are forms to store data. Currently, my goal is to ensure that the div that was ...

Looking for a solution to the problem: Module 'import-local' not found

internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'import-local' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modules/cjs/loader.js:520:25) Encoun ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Unexpected behavior with async/await in Vues.js

Despite appearing to run correctly, the console log indicates that the final result is being output before the inner await/sync. submitForm: function() { console.log("SUBMIT !"); // vee-validate form validation request const makeVali ...

Utilizing ReactJS to retrieve configuration settings from a YAML file, similar to how it is done

Our team is currently using a full-stack multi-microservice application where the backend java components utilize the spring @value annotation to fetch configuration values from a yml file. This method has been effective and even the Java side of our UI c ...