Issue encountered while transmitting data via Ajax and retrieving in the controller

When I send Json data, it arrives as null when I verify my method in the controller

Simplified HTML:

<div class="child">
                    @Html.LabelFor(m => m.Project, new { @class = "", style = "color:#040404" })
                    @Html.DropDownListFor(Model => Model.ProjectID, Model.Project, "Select")
                    @Html.ValidationMessageFor(Model => Model.Project, null, new { @class = "label label-danger", id = "Project" })
                </div>
<div class="child">
                    <input type="button" id="add" value="Add" class="myButton">
                </div>

JavaScript snippet:

$('#add').click(function () {
        debugger;
        var data= {
        Project: $("#ProjectID option:selected").text()
    };
    $.ajax({
        url: "../HandleData",
        type: "POST",
        dataType: "json",  
        data: JSON.stringify(data),
        success: function (mydata) {
            $("#UpdateDiv").html(mydata);
            history.pushState('', 'New URL: ' + href, href); // This Code lets you to change url howyouwant
        }
    });
}

Controller method:

public JsonResult HandleData(string Project)
    {
         ........
         ...
        return Json(Project);
    }

Error message in console:

https://i.sstatic.net/4V2lk.png

I'm unsure of what could be causing this issue. Any help would be greatly appreciated.

Thanks!

Answer №1

Your JavaScript code looks great, but I encountered an issue with the controller format not working as expected. However, I was able to find success by making some adjustments:

        [System.Web.Http.HttpPost]
        public HttpResponseMessage HandleData(string Project)
        {
            var data = " my test data ";
            return Request.CreateResponse(HttpStatusCode.OK, data);
        }

I will continue to investigate this issue and update my answer accordingly.

I hope this solution helps resolve your problem. Please let me know if you come across any further issues.

Answer №2

When working with the .Net framework, simple data types such as string, int, and float are typically retrieved from the query string, while complex types are usually retrieved from the request body.

Approach-1

In this scenario, the .Net Framework expects a string parameter named Proyecto to be passed through the query parameters when calling your API without requiring any changes to the server-side code.

Note: When using the [FromBody] attribute, there is no need to specify the parameter key in the HTTP request. Only one simple type can be passed using the [FromBody] attribute, as shown below:

POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded
=ProyectoValue

Approach-2

Alternatively, you can encapsulate all your parameters in a complex model and pass them through the request body rather than as query parameters:

Complex Type Model

public class MyModel
    {
        public string Proyecto{ get; set; }
    }

API Code

public JsonResult ManejoDatos(MyModel myModel)
    {
         //Access using mymodel.Proyecto
         ........
         ...
        return Json(mymodel.Proyecto);
    }

You can then consume your API by passing parameters through the body in the following manner:

POST ../ManejoDatos HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded

proyecto=myproyecto

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

"Troubleshooting a JSON structure containing a complex array of objects with multiple layers

I've structured a complex array with JSON objects to allow users to customize background images and create unique characters. Below is the main code snippet: var newHead; var newBody; var newArm; var masterList = [ { {"creatureName":"Snowman ...

Properties of variables

<Me:FunctionalParFractal runat="server" ID="stockNextDayProg" MinZ=" I ENJOY doing it dynamically" /> Although I am aware that it should be done from the controller side, I can't help but wonder if there is a way t ...

Are If-instanceof-statements considered harmful in Typescript?

selectAction: (actionEvent) => { if (actionEvent instanceof Action1) { // action1 body implementation } else if (actionEvent instanceof Action2) { // action2 body implementation } } This code snippe ...

The JSON string is failing to convert into an object

Attempting to send JSON from server side with the code below: $x = array(); $timestamp = strtotime('22-09-2008'); $x["x"] = $timestamp; $x["y"] = 22; $val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]'; ech ...

Update information without the need for page refresh

Check out my new Like button: <a class="wst-click" wst-href="{% url 'data:like' content.id %}" href="{% url 'data:like' content.id %}" >{{ data.likes.count }} Like</a> This code enables the 'Like' functionality w ...

Automatically pre-fill and send hidden form

I'm working on a form and have set up a handler for the submit button like this: $( '#submit_btn' ).click( function( data ){ theForm = document.getElementById( 'realForm' ); theForm.meetingName.value = document.getElement ...

Exploring Laravel 4: Controlling AJAX data manipulation via the controller

I am a beginner in using Laravel and ajax. Currently, I am working on retrieving data from a form through ajax and calling a controller method using ajax as well. The controller method searches the database and returns a json response to be handled by ajax ...

How can I load a specific div region using ajax for submitting a form?

I'm not sure if my approach is correct. On my main page, I have some information displayed. When you click a button, the form will load from a separate file: $('#viewport').load('/views/myView.php #targetDiv') This works fine ...

PHP receiving Ajax requests

Experimenting with a jQuery ajax post method on a localhost Apache 2.2 server running PHP 5.3 (completely new to this). Here are the files, all located in the same directory. Here is the HTML body with the form and included jQuery library: <form id="p ...

What could be causing the `daterange` to display an incorrect date?

While developing my ASP MVC application, I implemented a daterange picker which worked perfectly. However, when I moved the application to production on IIS, the daterange stopped working and displayed an "invalid date" error. https://i.sstatic.net/J6Ylf. ...

Exploring the world of Chrome extensions with jQuery

Starting my first Chrome extension and feeling a bit stuck. I've gone through the information on https://developer.chrome.com/extensions/getstarted I understand how to modify the pop-up page, but I'm unsure how to allow JavaScript to alter a tab ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

What is the reason for React.Component being implemented as a function rather than an ES6 class?

After delving into the codebase of React, I made an interesting discovery. When you define a class like class App extends React.Component, you are essentially extending an object that is generated by the following function: function Component (props, cont ...

Error: Unable to locate module: Unable to locate '@material-ui/core/Container'

Encountering an error in the browser: Error message: Module not found: Can't resolve '@material-ui/core/Container' The search for the component is directed towards my components directory instead of node_modules. Unfortunately, changing ...

Can you provide instructions on how to utilize the fingerprintjs2 library?

I'm diving into the world of device identification with fingerprintjs2, but encountering a roadblock due to my inexperience with Libraries. The error message I keep running into is Uncaught ReferenceError: Fingerprint2 is not defined. Take a look at ...

Unexpected token error encountered in AngularJS

Hey Team, I encountered an error while trying to add an employee. I'm looking for a way to dynamically add employees and display them on the list screen. Additionally, how can I access the employees from a different JS file? A SyntaxError occurre ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

Choosing a value at random from various returned results in a JSON format

I have written this code that works perfectly for a single return value. However, what if I need to handle multiple results and randomly select one? Here is my current code: class CheckSummonerLevel { public class GetVariable { public stri ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Apply specific inline styles to a designated div element

My task involves using the MURA CMS to create a form. While the form is functioning correctly, I am facing an issue where the Submit button is not centered. I would like to apply inline styling to the specific div that contains the Submit button (highlight ...