Encountering a problem with binding parameters while trying to submit JSON data to an MVC controller along with

I am currently struggling with posting a JSON object to an ASP.NET MVC controller without using Ajax. I have tried various methods but have not been successful so far. Here is what I have attempted:

  1. Backend Parameter Object
    public class Person 
    { 
        public string Name { get; set; }

        public string Email { get; set; }
    }
  1. Backend Controller
    public class BookingController : Controller
    {
        [HttpPost]
        public ActionResult AddPerson(Person person)
        {
            return View();
        }
  1. Frontend Javascript & Html
    <form action="/booking/addperson" method="post">
      <input type="hidden" name="person" id="person" />
      <button type="submit" class="btn btn-sm btn-primary">Submit</button>

      <script>
          var person = { "Name": "ML", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2afae82afeca1adaf">[email protected]</a>" }
          $("#person").val(JSON.stringify(person));
      </script>
    </form>

Unfortunately, the parameter in the controller was null when I submitted the form on step 3. However, I could see the actual data in the Request object inside the controller (refer to screenshot).

https://i.sstatic.net/5tM1d.png

Can anyone provide insights on how to successfully bind the JSON object to the controller parameter when posting a form? Any help is greatly appreciated! Thanks!

Answer №1

let personData = { "Name": "ML", "Email": "[email protected]" } $("#personData").val(JSON.stringify(personData));

This snippet of code is designed to convert the value of #personData into a string, but it may result in a null value due to using an object type in the backend handling.

To resolve this issue, you can modify your AddPerson method as shown below:

[HttpPost]
    public ActionResult AddPerson(string personData)
    {
        Person model = JsonConvert.DeserializeObject<Person>(personData);
        return View();
    }

Update

Alternatively, you have the option to update your view code like so:

<form action="/booking/addperson" method="post">
   <input type="hidden" name="name" id="name" />
   <input type="hidden" name="email"  id="email"/>
  <button type="submit" class="btn btn-sm btn-primary">Submit</button>

  <script>
      let personData = { "Name": "ML", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a0cdcce0cd8ec3cfcd">[email protected]</a>" }
      $("#name").val(personData.Name);
      $("#email").val(personData.Email);
  </script>
</form>

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

Issues involving JavaScript and jQuery

As a beginner in the world of JS and jQuery, I have encountered a problem that I am seeking assistance with. I am trying to use a script to insert content into a page, but I am facing a roadblock that I can't seem to overcome. Here's the specific ...

Trouble with two dropdown selections in Angular and preset values

I am encountering an issue with a select input in angular 7. The scenario involves having 2 selects where selecting an option in the second select populates the corresponding values in the first select. The first select should display a default placeholder ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

How to automatically generate a serial number using JavaScript each time a click event occurs

continuous problem with repeated serial numbers Serial number remains the same after each click $(document).on('click', '.menu-item', function() { var menu_id = $(this).attr('id'); var _token = $('input[name="_ ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Numerous Controllers in AngularApp failing to function properly

One issue I'm encountering is that only one out of the two controllers within my app seems to be registered: var app = angular.module('MyModule', []); app.controller('FruitCtrl', function($scope) { $scope.fruits = ['appl ...

Tips on adjusting the placement of a div element with JavaScript

Initially, I am unsure if the title accurately reflects what I am seeking. Within my HTML form, I have numerous elements such as div, p, or js. Here is an example: <div id="main"> <div id="abc1"></div> <div id="abc2"></div&g ...

Comparing the size of a MongoDB array to another field in a document: how can it be done?

Need guidance on querying MongoDB for documents that have a specific number of users in them. This needs to be done through both the mongo console and JavaScript in Node.js: db.turnys.find( { users:{$size:seats } } ) The structure of turnydb.turnys colle ...

JS: Best way to transfer selected information to the following page?

Within our SharePoint list, users often need to add very similar items. To streamline this process, I am exploring the possibility of adding a new column that includes a button or turning one of the existing columns into a clickable link. When clicked: ...

Why is it that the .forEach() function has the ability to alter the Vuex state?

After extracting two sets of balances from my vuex state, I decided to merge them into a new array of entries. However, an error is thrown when I try to loop through my copies of the vuex state. Am I missing something? It seems that the issue lies in the ...

The AJAX request successfully retrieves data, but the page where it is displayed remains empty

I have come across similar questions to mine, but I have not been successful in implementing their solutions. The issue I am facing involves an AJAX call that is functioning correctly in terms of receiving a response. However, instead of processing the re ...

Retrieve an XML document using AJAX and then convert it to JSON format without needing a server

Seeking assistance with a code snippet I'm currently working on. Unfortunately, my knowledge of AJAX and jQuery is limited. Here's the issue: I am trying to retrieve XML data from an external XML file (text.xml) and convert it into a JSON object ...

Using AJAX, SQL and PHP to send data to a separate page for processing

This is the code I use to retrieve questions via ajax from a list of questions stored in a SQL database. <form id="reg-form3"> <ul class="nav nav-list primary push-bottom"> <? $db['db_host']="localhost"; ...

Adding elements to a multi-dimensional array that match elements from another array

I am working with two arrays: a = [ [a, b], [c, d], [e, f], [g, h] ] b = [ [a, 4], [1, 2], [e, 3] ] My challenge lies in updating the elements of array a when they match corresponding elements in array b. Specifically, I need to add a new ...

Jquery Datatable failing to display data on screen

For displaying data, I have implemented Jquery Data table using an ajax call and a JSON file. The setup includes two tables - #list1 shows SQL data while #list2 gets populated when a row in the first table is clicked (click event). However, I encountered i ...

Sending files in Express causes issues

I keep receiving the following message: express deprecated res.sendfile: Use res.sendFile instead Here is the code snippet in question: app.get('/*', function (req, res) { var myUrl = req.url.split('/')[1]; myownfunction(myUrl ...

Firebase Admin refuses to initialize on a Next.js application that has been deployed on Firebase

Currently, I am facing an issue while attempting to deploy a Next JS app to Firebase hosting using the web framework option provided by firebase-tools. The problem arises when trying to initialize firebase-admin as it seems to never properly initialize whe ...

Add an element to the jQuery collection before the last element, not at the end

My challenge lies in utilizing AJAX to post a comment. However, the last comment element features a submit button within it. Consequently, whenever a new item is appended, it appears after the submit button. <div class="commentContainer" > < ...

Tips for attaching functions to a fresh SVG element with jQuery?

My jQuery code creates an <svg> element and appends it to a <div>. When I try to access the appended <svg> using each() after the append() function, the event handler doesn't work. However, if I create the <svg> element before ...

Encode URLs using JSON in C# similar to how it is done in PHP

While working with PHP and using the json_encode function to encode an object into JSON format, I noticed that URLs in the output are converted into strings with escape characters like http:\/\/example.com\/apps\/images\/image01.jp ...