Unable to convert JavaScript object to C# through deserialization

In order to pass a model from the controller action to the view, I included a list of objects and converted it into a JavaScript object to facilitate displaying markers on Google Maps. My goal is to send the selected object (selected marker) back to the controller action when the marker is clicked.

@model List<FleetDesignerMVC.ViewModel.VehicleFullInformations>

<body>
    <div style="width:100%; height:650px" id="map"></div>
</body>

<script>
function initMap() {
  var initialLatLang = {lat: 36.862499, lng: 10.195556};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: initialLatLang,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

    //CONVERT CONROLLER MODEL TO JAVASCRIPT OBJECT
    var model = @Html.Raw(Json.Encode(Model));

    var infowindow = new google.maps.InfoWindow;

    //CREATING MARKERS
    for (i = 0; i < model.length; i++) {
      marker = new google.maps.Marker({
          position: new google.maps.LatLng(model[i].VehicleCurrentPosition.Latitude, model[i].VehicleCurrentPosition.Longitude),
          map: map,
          icon: model[i].Vehicle.MarkerPicture
      });


      google.maps.event.addListener(marker, 'click', (function (marker, i) {
          return function () {
              infowindow.setContent('<table>'+
      '<tbody>'+
      '<tr>'+
          '<td><img src="' + model[i].Vehicle.VehiclePicture + '" alt="imageed" width="150" height="150" /></td>'+
          '<td>'+
              '<table>'+
                  '<tbody>'+
                      '<tr>'+
                          '<td><h5>' + model[i].Vehicle.Matricule + '</h5></td>'+
                      '</tr>'+
                  '<tr>' +
                  '<td>Date: ' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getDate() + '/' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getMonth() + '/' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getFullYear() + '</td>' +
                  '</tr>' +
                  '<tr><td>Hour: ' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getHours() + ':' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getMinutes() + ':' + new Date(parseInt(model[i].VehicleCurrentPosition.TrackDate.substr(6))).getSeconds() + '</td></tr>' +
                  '<tr>'+
                      '<td>'+
                          '<p>Speed: ' + model[i].VehicleCurrentPosition.Speed + ' Km/H</p>'+
                      '</td>'+
                  '<tr><td> <button onclick="postData(\'' + model[i]+ '\')">Send</button> <\/td><\/tr>' +
                  '<\/tbody>'+
              '<\/table>'+
          '<\/td>'+
      '<\/tr>'+
      '<\/tbody>'+
      '<\/table>');
              infowindow.open(map, marker);
          }
      })(marker, i));
    }
}

function postData(model) {
    var f = {};
        f.type = "POST";
        f.url = '@Url.Action("Index", "VehicleDetails")';
        f.contentType = "application/json; charset=utf-8";
        f.data = JSON.stringify({model});
        f.dataType = "json";
        f.success = function (response) {
            alert("success");
        };
        f.error = function (response) {
            alert("failed");
        };
        $.ajax(f);
};
</script></pre>
<blockquote>
<p>This is the structure of my model:</p>
</blockquote>
<pre><code>public class VehicleFullInformations
{
    public Vehicle Vehicle { get; set; }
    public Brand VehicleBrand { get; set; }
    public Model VehicleModel { get; set; }
    public VehicleType VehicleType { get; set; }
    public GpsTrack VehicleCurrentPosition { get; set; }
    public FuelType VehicleFuelType { get; set; }
}

Although the markers are displayed correctly on the map, there seems to be an issue when selecting one and clicking the send button. The sent object appears as [object object], which results in a deserialization error "Invalid JSON primitive: object".

This is the code snippet from my action method:

[HttpPost]
public ActionResult Index(string model)
{
    var jss = new JavaScriptSerializer();
    var dataObject = jss.Deserialize<VehicleFullInformations>(model);
    Console.WriteLine(dataObject);
    // .. do something with data object 
    return Json("OK");
}

If you have any suggestions or insights on how to resolve this issue, please feel free to share. Thank you in advance for your assistance, and apologies for any language barriers.

Answer №1

Be cautious when using <code>f.data = JSON.stringify({model})
. This code snippet creates an object with the variable model nested inside. The resulting object structure will be:

{
  model: {
    ... your actual model ...
  }
}

To avoid wrapping your JS model in another object, consider using f.data = JSON.stringify(model) instead.

If you're debugging, try setting a breakpoint at

var dataObject = jss.Deserialize<VehicleFullInformations>(model);
and inspecting the value of model in C# to ensure it contains the expected data.

UPDATE

It's likely that

<button onclick="postData(\'' + model[i]+ '\')">Send</button>
is not functioning as intended. Check the button element using your developer tools after the page loads - it may display something like
<button onclick="postData('[object object]')">...

To rectify this issue, consider modifying the code to something like

<button onclick="postData(' + i + ')">...
followed by:

function postData(modelIndex) {
   let postModel = model[modelIndex];
   ...
       f.data = JSON.stringify(postModel);
   ...
}

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

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

Looping through a nested for loop within an HTML table

I am currently working on generating a dynamic table using Lists of varying sizes. My first list is a List of Cars List<Car>. I have successfully placed the names of different car companies in the header. Next, I have a List<List<CarSales>& ...

Passing the outcomes of several queries to a single route in my application, and displaying them on my

Currently, I am facing an issue with fetching 2 sets of data from my database using simple MongoDB queries. I need to pass both results to the view, but I am encountering an internal server error. My goal is to display a complete list of guardians along wi ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

Error: The function preciseDiff is not recognized by moment

Encountering an error message: "TypeError: moment.preciseDiff is not a function. I am facing the same issue, wondering if there is a solution or alternative available. I have version 2.24.0 of moment installed. moment-precise-range-plugin In addition, I ...

Tips for displaying dynamic data using innerHTML

Recently, I set out to implement an infinite scroll feature in Angular 2 using JavaScript code (even though it may seem a bit unusual to use JavaScript for this purpose, it's actually working perfectly). Initially, I was able to create an infinitely s ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

Building Form Auto Complete Functionality on Google's App Engine

Looking to create an autocomplete feature for a tags field similar to Stack Overflow on the App Engine platform. Does anyone have suggestions on how to approach this? Regarding the server-side algorithm, what kind of logic should be implemented for the au ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

Leverage a JavaScript function to manipulate the behavior of the browser's back button

Is there a way to trigger the Javascript function "backPrev(-1)" when the back button of the browser is clicked? Appreciate any help, thank you. ...

What is the optimal location for making API requests in a React/Redux/Reach Router application?

I'm struggling to figure out the optimal location for making API calls in my app. My main component structure looks like this: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Utilizing Puppeteer to Navigate and Interact with Elements Sharing Identical Class Names

I am new to Puppeteer and NodeJs, and I am attempting to scrape a specific website with multiple posts that contain a List element. Clicking on the List element loads the comment section. My question is: I want to click on all the list elements (since th ...

Sending information through a form via a POST request after clicking on a hyperlink

I am attempting to submit a form using POST by clicking on a link and passing some hidden values. This is the code I'm currently using: $( document ).ready(function() { $('a#campoA').click(function() { $.post('testForm2.php', { ...

sending a file using ajax and handling it with php

Curious if there's a way to upload a binary file through ajax and php, without having to refresh the entire page like with a traditional html form. I've been able to gather input from radio buttons and text boxes using forms and javascript, but w ...

React is unable to identify the `activeKey` property on a DOM element

First and foremost, I am aware that there have been a few inquiries regarding this particular error, although stemming from differing sources. Below is the snippet of my code: <BrowserRouter> <React.Fragment> <Navbar className=& ...

The jQuery AJAX call is successful in Firefox, but unfortunately, it is not working in Internet Explorer

I've encountered a perplexing issue with an AJAX call. It's functioning perfectly fine in Firefox, but for some reason, it's not working in IE. Curiously, when I include an alert() specifically for IE, I can see the returned content, but the ...

The node.js API request is experiencing a unresponsive state

As a newcomer to the world of JavaScript, I am currently learning the basics of Node.js. One task I'm working on involves retrieving a contact from my mongoDB and creating a GET method to return it. Sounds simple, right? Below is the router method I ...

What is the best way to apply a CSS class to a div element without affecting its child elements using JavaScript?

Currently, I am using JavaScript to add and remove a CSS class through a click event. Within my div structure, I have multiple similar divs. While I can successfully add and remove the class from my main div, I am facing an issue where the class is also ap ...

Creating lottery numbers with the help of AJAX and PHP

Can someone help me figure out how to generate lotto numbers using PHP, MySQL, and Ajax? I would like to create a similar number generator as shown here: Any advice on the logic or method to achieve this would be greatly appreciated. Thank you in advance! ...