Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller:

public JsonResult GetRights(string ROLE_ID)
        {
            var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

The dropdownlist creation code:

@Html.DropDownList("ddlRoles", new SelectList(ViewBag.Roles, "ROLE_ID", "ROLE_NAME"),"--Select role--", new { onchange = "GetRights(this.value);" })

Lastly, a javascript snippet for handling dropdown item change:

<script type="text/javascript>
        function GetRights(role_id) {
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetRights")',
                dataType: "json",
                data: { "ROLE_ID" : role_id.toString() }, 
                success: successFunc,
                error: errorFunc
            })
        }

        function successFunc (data) {
            alert("success");
            if (data != null) {
                var vData = data;
            }
        }

        function errorFunc() {
            alert("error");
        };
    </script>

Although the javascript function is triggered when changing selection, I am unable to navigate to the controller method. Can someone help me identify the issue? Thank you.

Answer №1

It's important to remember that when using AJAX to perform a GET request, the parameters should be passed in the URL string. Your AJAX URL parameter should follow this format:

http://someaddress/GetRights?ROLE_ID=sometexthere

You can verify where your request is being fired from by checking the browser console or debugger. Additionally, you can manually trigger the same request from the browser since it is a standard GET method.

Answer №2

Realized my mistake now. It was silly of me. I had mistakenly commented out the following:

@Scripts.Render("~/bundles/jqueryval")

Unfortunately, I didn't notice that :(. I have now added jQuery and everything appears to be working correctly. I appreciate everyone's assistance

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

Generating dynamic dropdown lists with JavaScript for variable arrays

I've been scouring the internet for quite some time now, both on this platform and through Google searches, but I can't seem to find what I'm looking for. (Apologies if I missed it and this comes across as a repetitive or annoying question.) ...

A step-by-step guide on building a custom contact form using ReactJS and transmitting the data through an API with Express

In my quest to utilize ReactJS for building a contact form and seamlessly sending the data to my email address, I embarked on creating a contact form within my App.js file. import React, { Component } from 'react'; import axios from 'axios& ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Crafting artistic shapes using the Canny Edge Detection technique on Canvas

Can someone provide some guidance on using Canny Edge Detection to generate shapes in Canvas? ...

Ways to convert a JavaScript object's properties into JSON format

I am currently manually going through the properties of my javascript class to create JSON, as shown below. It feels cumbersome and I am looking to automate this process so that I don't have to make changes to the 'toJson' function every tim ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

Is it possible to create an instance of a superclass and automatically instantiate a specific subclass based on the parameters provided?

Currently, I am utilizing Google's GSON package which can be found at this link My task involves converting JSON data to Java objects. Below is a snippet of the code where the conversion process takes place: Gson gson = new Gson(); Type collectionT ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Prevent Repeated Data Input in an Array using JavaScript

I am facing an issue where I need to ensure that the values being inserted are not repeated when performing a push operation. Below is the snippet of code in question: addAddress: function() { this.insertAddresses.Address = this.address_addres ...

The HTML page is displaying the Express.js GET request

As a beginner in express.js, I'm encountering an issue where data sent to the client is displayed directly in the browser instead of appearing as a preview. Can someone please review my code and help me identify what I'm doing wrong? app.use(cors ...

Utilize Jquery to hide radio buttons, while allowing users to click on an image to display a larger version

My current HTML structure is restricted to SAAS, so I only have control over jQuery implementation. https://i.stack.imgur.com/OHB9K.jpg I am attempting to achieve a similar layout as shown in the image below. The main issue lies in how to (1) conceal ...

An issue has been identified with the functionality of an Ajax request within a partial view that is loaded through another Ajax request specifically in

Here is the current scenario within my ASP.NET MVC application: The parent page consists of 3 tabs, and the following javascript code has been implemented to handle the click events for each tab: Each function triggers a controller action (specified in t ...

It appears that the Facebook share feature is not picking up any meta OG tags

There seems to be an issue with my Facebook share functionality as it's not reading any of the meta tags. It is indicating that the required properties such as og:url, og:type, og:title, og:image, og:description, and fb:app_id are missing. <script ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

The output from the Web API Controller model is empty

I am encountering an issue where the Web API controller with FROMBody always returns a null model. The model for a Product object includes ProductID and a List of Order objects: public class ProductModel { [Required] public string productID { get ...

Avoid the resetting of chosen value following a POST or submission

I am currently working on creating a "web dashboard" that requires a year_from parameter from an HTML form. Despite setting up my Flask backend to return data within this specified range, I am encountering a problem where every time I hit submit, the selec ...

Learn how to implement a captivating animation with JavaScript by utilizing the powerful Raphael Library. Unleash the animation by triggering it with either

My desire is to indicate this movement by triggering a mouse click or drag to the desired location. let myDrawing = Raphael(10,10,400,400); let myCircle = myDrawing.circle(200,200,15); myCircle.attr({fill:'blue', stroke:'red'}); let my ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

The incorrect sequence of Angular/Protractor functions is causing issues within the tests

Trying to extract the values from a column in a grid and compare them before and after sorting can be tricky. I have two functions set up for this task - one to retrieve the initial column values, and another to check the order post-sorting. However, there ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...