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

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

The event.pageY position consistently reflects the laptop screen size rather than the exact position where the click occurred

My webpage is scrollable, but the event.pageY position always corresponds to my screen size. Even when scrolling down and clicking near the top of the screen, it registers as 50px. I am currently utilizing event.pageY While this functions correctly on a ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

The loading process in CSS can be customized using unique IDs such as loading1 and loading300

My current CSS code looks like this: #loading{ display:none; } The issue I am facing is that I need to hide multiple loading divs, each with an id that includes the word "loading". For example: <div id=loading1></div> <div id=loading42 ...

Is there a simpler method to access the source element for an event?

I'm just starting to learn JavaScript and jQuery, and right now I have the following code in my HTML: <a id="tog_table0" href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a> After that, I hav ...

Utilizing OData in combination with specialized WCF WebGet functions

I have developed an OData endpoint using Entity Framework and WCF Data Service. In addition, I have included a custom WebGet test method as shown below: [WebGet(UriTemplate = "{text}")] public IQueryable<string> SplitString(string text) ...

Contrasting an array of items with an array of Objects

I need to match the values in an array called ingredientName with a corresponding array of objects. Here is how they look: const ingredientName = ['chicken', 'cheese', 'tomato', 'lettuce']; let imageObjects = [ { ...

What are the steps to refreshing a table using AJAX?

Struggling to update a table from my database, I have been following a PHP guide but can't get it to work. In a separate file, the data is retrieved and displayed in a table. I am attempting to use JavaScript to refresh this file. This code snippet ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

Securely Saving JWT Tokens from Auth0 Login in Node.js Express

As a novice in the world of Auth0, I am currently working on integrating it into my regular express web application. My main goal is to secure and validate users before they are able to access certain endpoints. From what I have gathered, this can be achie ...

Tips on extracting data from an API using jQuery

Struggling with parsing data and feeling a bit stuck. That's why I'm reaching out for assistance. This is where I need help: How do I specifically retrieve market_cap values? Each value needs to be accessed individually for a specific string I ...

The error "clearRect is not defined in javascript" occurs when the property is being called on an undefined object in the JavaScript

I've encountered a similar question before, but unfortunately, the solution provided didn't help me! I'm relatively new to JavaScript and have been struggling with this issue for nearly a day now without success. The structure of my class a ...

The jQuery button function is not compatible with Google Graph

Upon review below, I have successfully created the getChart() function. It functions properly when called independently, however, it fails to display the chart when enclosed within $(document).ready(function(){...}). The file is also attached for referen ...

Selectize Fails to Populate Options Using Ajax

ExpressJS is the platform I am using to develop a management dashboard for a community project. Right now, my main concern is integrating a modal that allows users to add new games to a database. Although I am able to fetch data remotely, I am facing diffi ...

Setting the backEnd URL in a frontEnd React application: Best practices for integration

Hey there - I'm new to react and front-end development in general. I recently created a RESTful API using Java, and now I'm wondering what the best way is to specify the backend URL for the fetch() function within a .jsx file in react. Currently, ...

Exploring data elements using iteration in JavaScript

Here is some code that is functioning properly: Morris.Bar({ element: 'barchart', axes: true, data: [ json.bar.bar1 ], xkey: 'x', ykeys: ['y', 'z', ' ...

Executing JavaScript Code Through Links Created Dynamically

I am currently developing a website with a blog-style layout that retrieves information from a database to generate each post dynamically. After all posts are created, the header of each post will trigger an overlaid div displaying the full article for tha ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component: <template> <div> <div id='geocoder'></div> </div> </template> <script> import mapboxgl from 'mapbox-gl& ...

Scrolling vertically in an ASP.NET GridView

I have a Grid View embedded inside an IFrame. Everything works perfectly when the number of records fits within the frame. However, if I try to display more records, I encounter an issue where I am unable to click on the Footer Row. It automatically moves ...