Using getJSON to call the Controller in .cshtml

I successfully executed this action in a .js file without any complications, but now I'm facing difficulties implementing it in a .cshtml file. Despite thorough investigation, I can't identify any other potential reasons for this failure. Below is the JavaScript code written within my .cshtml file:

mergeBtn.onclick = function (e) {
    e.preventDefault();
    var url = '/api/publicpatron/student-no-validation?studentNo=' + studentNo.value;

    $.getJSON(url)
    .done(function (json) {
        if (json.errors) {
            toastr.error(json.message, '', { timeOut: 0, extendedTimeOut: 0 })
        }
        else {
            //do something
        }
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus = ', ' + error;
        toastr.error(err, '', { timeOut: 0, extendedTimeOut: 0 })
    })
}

The issue doesn't seem to lie in the controller code as it never reaches the controller itself. I've double-checked the file and function names in the URL, so that shouldn't be causing the problem. Any suggestions on what could be going wrong? Is executing this from a .cshtml file not feasible???

UPDATE:

Below is the information about the controller:

File name: PublicPatronController

[Authorize(Roles = "my-roles")]
[ActionName("student-no-validation")]
public dynamic IsStudentNoValid([FromUri] string studentNo)
{
    dynamic results = new ExpandoObject();

    if (studentNo == null)
    {
        results.error = true;
        results.message = "Invalid Student Number";

        return results;
    }

    using (ADRoutineEntities db = new ADRoutineEntities())
    {
        var exists = db.UserLinkages.Any(x => x.StudentNo == studentNo);
        if (!exists)
        {
            results.errors = true;
            results.message = string.Format("Student number {0} does not exist", studentNo);

            return results;
        }
    }

    results.ok = true;

    return results;
}

UPDATE 2: It seems like the issue might be related to the controller after all. I switched the URL to a different apicontroller used elsewhere, and it worked perfectly. It appears that the problem lies with the name of the apicontroller. When I switch it to an existing apicontroller while keeping the actionname the same, everything works fine. Why do you think this is happening???

Answer №1

Make sure to include the [HttpGet] attribute in your controller method.

In most cases, WebAPI automatically determines the HTTP verb based on the method name. However, in this scenario, it's necessary to specify the attribute because the method name does not correspond to a valid HTTP method.

Alternatively, you can modify the method name to something like GetIsStudentNoValid.

Instead of using dynamic, consider returning an HttpResponseMessage with an appropriate status code.

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

Error encountered during the execution of the store method in Ajax CRUD operation

Greetings, I'm encountering an error in my AJAX code every time I try to execute the store function https://i.sstatic.net/SW86I.jpg Below is my controller: public function store_batch(Request $request) { $rules = array( 'batch_name& ...

Converting a C# two-dimensional array into JavaScript formatting

Is there a more streamlined method for converting a two-dimensional array in C# like [[1, 2, 3],[4, 5, 6]] into a string representation "[[1, 2, 3],[4, 5, 6]]" without manually iterating through each value and formatting it? I want to pass the array as an ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

What is the best way to add a button to every row in Titanium Studio?

Is there a way to add a different button inside each row (createTableViewRow)? I have created five buttons using Titanium.UI.createButton, but I'm struggling to figure out how to place all five buttons in every row. Can someone provide some guidance o ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Errors have popped up unexpectedly in every test file after importing the store into a particular file

Using Jest and Enzyme to test a React application has been successful, but encountering failures when importing redux store in a utility file. The majority of tests fail with the following error: FAIL app/containers/Login/LoginContainer.test.js ● Te ...

Sending a variable from JavaScript to an external PHP file

There are numerous questions on similar topics, but I'm struggling to figure it out, my apologies. I have a file containing some JavaScript variables that depend on user input (without using a form) and a normal HTML link to my PHP file. <script& ...

Resolving Node.js email attachment problem by selecting a file using Postman form-data

Hello, I am currently experiencing difficulties with sending email attachments. Can you please advise me on how to send a file that I have selected from form-data in Postman? How do I specify the path of the file? //const Joi = require('joi'); c ...

Generate an Array reference using the index of elements instead of duplicating the values

When initializing b, it appears that the array data is being copied from a instead of referencing it, as originally intended: let a = [0,1]; let b = [a[0], 2]; a[0]=3; console.log(b); The resulting output is 0,2. What is the reason for the output not ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...

Tips for updating the background color of the current day in a jquery datepicker when clicked

In my AngularJS project, I have implemented a jQuery datepicker. To make the current date stand out, I customized the CSS to display it with an orange background: .ui-state-highlight{ background-color:orange; } However, there is now a new requirement ...

What is the best way to convert special fonts into JSON using php?

I have an array that looks like this: Array ( [0] => Array ( [image] => http://domain/photogal/tues/image/2012octo30big11.jpg [news] => 'ssN ^mj³ ho¡n dm¼nse¯nb tamUÂ<br> ' ) ...

Issue encountered while requesting data from API in ReactJS

I've been trying to fetch data from using the react useEffect hook. However, instead of displaying the data, I keep getting an error message that says, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you me ...

Ways to adjust the visibility of the table of contents based on varying screen sizes

I am currently using a JavaScript code to dynamically generate a table of contents from H2 tags, and it's working flawlessly. However, I would like the table of contents to have a status of "Hide" (requiring clicking on "Show" to display the table of ...

What are the advantages of incorporating JSON for retrieving data from MySQL?

So I have developed a website that retrieves data from a MySQL database using PHP, and then transforms it into JSON format for use with JavaScript. This process can be broken down into 5 steps: Query -> PDO Statement -> PHP Array -> JSON Strin ...

Clicking the submit button in JavaScript will trigger a request to the Spring MVC backend,

When I use the following code, it gives me an object response: @RequestMapping(value = "/NewLogin",method = RequestMethod.POST) public @ResponseBody Token getAllBooks( Token token = new Token(); token.setValue(encryptedMessage); return toke ...

Display only the posts of the logged-in user in a React application

I need assistance with a React return that displays only the posts of each logged-in user. Currently, my code loads all posts from all users and shows only the posts from the user who is currently logged in. However, the other posts still take up screen s ...

Every time I try to restart my React Project, it seems to encounter strange issues that

Currently, I am following a fullstack React tutorial which you can find here: React Tutorial I have encountered an issue where every time I close my laptop and reopen the project, npm start throws a strange error. Initially, I tried to fix it by starting ...

Using Lightmaps with Three.js

Is it true that lightmaps function independently of other textures? It seems like I need to establish a second set of UVs. I've exported my JSON object with a second set of UVs and included the following code snippet: geometry.faceVertexUvs[0] = ge ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...