Resolving the issue of passing a null value from Ajax to an MVC controller

I need to pass a value to an MVC action,

below is the JavaScript code:

function functionName(Name) {
        $.ajax({
            url: "/Home/GetName",
            type: "POST",
            dataType: "json",  
            data:JSON.stringify({ 
                Name: Name
            }),
            success: function (mydata) {

            }
        });
        return false;
    }

and here is the corresponding MVC action:

[HttpPost]
public JsonResult GetName(string Name)
{
       return Json(new { oid = Name});
}

Despite successfully printing the value "Name" before sending it to the action, it is received as "null" on the server.

Answer №1

Stephen, as mentioned in the comments, is absolutely right. The correct solution involves making the following adjustment:

data: JSON.stringify({ 
                Name: Name
            }),

should be modified to

data: { Name: Name } 

Answer №2

Give it a shot with this addition:

contentType: "application/json"

as shown below

 function newFunction(NewName) {
    $.ajax({
        url: "/Home/UpdateName",
        type: "POST",
        dataType: "json",  
        contentType: "application/json",
        data: JSON.stringify({ 
            NewName: NewName
        }),
        success: function (responseData) {

        }
    });
    return false;
}

I believe this alteration will prove beneficial, :)

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

What is the process for embedding a section of content from a different webpage into a separate division on my website?

Is there a way to pull content from one webpage and display it on another? Would using an Iframe be the best solution for this task? Thank you in advance for your assistance! ...

Unable to delete element from the given array

I have been working on removing instances of 'store.state.location.locations' from my locationData array that should no longer be there, but for some reason, they are persisting in the array even though I am no longer passing those instances. ta ...

Scraping dynamic content with Python for websites using JavaScript-generated elements

Seeking assistance in using Python3 to fetch the Bibtex citation produced by . The URLs follow a predictable pattern, enabling the script to determine the URL without requiring interaction with the webpage. Attempts have been made using Selenium, bs4, amon ...

Convert a DateTime object to JSON using the Mongo C# driver's toJson

I have a dataset stored in MongoDB that looks like this: "trd" : ISODate("2003-12-08T00:00:00Z") Currently, I am retrieving data from Mongo as BsonDocument using the following approach: var builder = Builders<BsonDocument>.Filter; var ...

Adding Event Handlers to Controls in a class that inherits ITemplate

I have created a custom template for adding controls to a DetailsView programmatically. private class CustomFooterTemplate : ITemplate { private Button btn_Edit; public void InstantiateIn(Control container) { btn_Edit = new Button(); ...

An issue arose with ReactDom during the development of the application

I am currently working on my final assignment for the semester, where I have created a project and finished coding it. However, when I try to load the localhost, the page remains blank even though the console in vsc shows no errors. Upon checking the conso ...

Attempting to display an external webpage within a popup window on my ASP.NET MVC3 application

I am working on an ASP.NET MVC 3 website that needs to display a card validation page in a popup. The challenge is that the card validation page belongs to an external website and cannot be modified. One of the requirements is to make a POST request to thi ...

What is the procedure for extracting data from a JSON file within an HTML document?

Hey there, I am currently working on reading data from a json file using ajax. I have created a Video object that consists of Courses objects with titles and URLs. However, when attempting to read the title and URL of HTML as an example, I am not seeing a ...

How do I synchronize my chart updates with my paginated datatable using Asp.Net C# MVC4 and Json?

Currently, I am utilizing datatables and charts for my project. My preference is to return standard data via the model, but unfortunately, it seems that only Json works with the controls. This lack of understanding has left me feeling completely lost. In ...

Ways to substitute PHP functions using AJAX

I'm a beginner with AJAX. How do I replace the initial PHP function after an AJAX action is executed? It seems that the page does not refresh after the action takes place. Below is the code: Javascript function set_ddm(another_data) { var resul ...

What is the most effective method for assessing a service using angular?

As a beginner in angular testing, I am eager to start creating tests for my service. However, I have encountered an issue where my service (foo) injects another service (bar) in its constructor. Should I create a mock for bar? Do I need to mock every func ...

Manage the dimensions of elements using Javascript on the client side

Here is a form I created: <form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp"> <input type="file" name="pho" id="photo" class="inph" accept="image/*"> <button type="submit" id=" ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Maintain GoogleMaps map object across different views in AngularJS

I have made the decision to utilize the AngularUI Map plugin for displaying Google Maps within a specific view. Here is how the template is structured: <div id="map"> <div ui-map="map" ui-options="mapOptions" id="map-canvas" ui-event="{&apo ...

Unexpected token encountered when testing Ajax call with JSON response

Currently, I have a Vue application with the following code snippet... var vm = new Vue({ el: '#Workbooks', components: { 'workbook-list': workbooklist }, data: { workbooks: [], message: '', loading: true, ...

What could be causing my Express React application to fail to load?

Struggling to post here, can't get the title right. Hello everyone! Dealing with an error: Invalid hook call. Want to debug this issue? Check out this link. Issue arises after importing material-ui. Here is my code: import {Container, AppBar, Typogra ...

Results From Trimming Data

There's a function in my code that fetches data from a database. The problem I'm facing is that the function is returning values with extra quotation marks. Before displaying these values on the user interface, I need to trim them. This is the f ...

What is the best way to download a vast number of files with nodejs?

I have a total of 25000 image links that I need to download to my local machine using the request package in nodejs. It successfully downloads up to 14000 to 15000, but then I start encountering errors. Error { Error: socket hang up at TLSSocket.onHa ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Tampermonkey feature: Extract source code with a button click from a constantly updating AJAX page

My goal is to create a simple script that can copy the source code of a dynamic AJAX page whenever I press a button. The current code, which I have included below, seems to be working fine: // ==UserScript== // @require http://ajax.googleapis.com/ajax/li ...