What is the best way to transform a database object into a complex JSON structure?

My goal is to retrieve a specific person from a list of persons. The POST method works correctly and I am able to obtain the desired person as "chosenPerson" in the controller. However, when I try to convert this person into a complex JSON object using serializer.Serialize(chosenPerson), an exception occurs with the following message:

An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code

Further details: Exception has been thrown by the target of an invocation."

Here is the JavaScript code within the view:

$.ajax({
    type: 'POST',
    url: '@Url.Action("ReturnPerson", "Home")',
    contentType: 'application/json; charset=utf-8',
    data: emailUnique,
    error: function (event, jqxhr, settings, thrownError) {
        console.log(event + " || " + jqxhr + " || " + settings + " || " + thrownError);
    }
});
chosenPerson = $.getJSON('/Home/ReturnPerson/');

As for the controller:

[HttpPost]
public ActionResult ReturnPerson(string emailUnique)
{
    var db = new CvAdminContext();
    var chosenPerson= db.Persons.Where(p => p.Email == emailUnique);
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    return Json(serializer.Serialize(chosenPerson), JsonRequestBehavior.AllowGet);
}

Answer â„–1

Your code has a few errors that need to be addressed. It is recommended to utilize the Newtonsoft.Json library for serializing the Json data. Additionally, I have removed the [HttpPost] attribute. Modify your controller as follows:

public JsonResult GetPersonDetails(string email)
{
    var context = new CvAdminContext();
    var selectedPerson = context.Persons.Where(p => p.Email == email).ToList();

    return Json(JsonConvert.SerializeObject(selectedPerson), JsonRequestBehavior.AllowGet);
}

On the client side, you can then proceed with the following approach:

var userEmail = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7a4bbb2a79390a393b7a4bb99bbc798a4bbb2939fbdb0">[email protected]</a>";
// Alternatively, you can also use var userEmail = @Model.Email; if the view is strongly typed.

var personData = $.getJSON('/Home/GetPersonDetails?email=' + userEmail, function(data) {
    console.log(data);
});

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

Unable to display individual elements of an array using the map function in React Native

Below is my react-native code that I am using to display a list of array elements using the map function. import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import {Card} from 'react-native-e ...

Changing the font family for a single element in Next.js

One unique aspect of my project is its global font, however there is one element that randomly pulls font families from a hosted URL. For example: https://*****.com/file/fonts/Parnian.ttf My page operates as a client-side rendered application (CSR). So, ...

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

React: Struggling to retrieve specific elements from an array stored in component state

For a fun side project, I've taken on the challenge of creating a miniature Pokedex app using React. import React, { Component} from 'react'; import './App.css'; import Card from './components/card/Card.component'; clas ...

The navigation bar in React Router is interfering with the loading of other components

Currently, I am in the process of setting up a simple navigation bar that consists of basic buttons without any complex functionality. However, I have encountered an issue where placing the navbar inside the switch prevents other components from loading ...

The close menu button is not functioning properly when clicked outside the menu - the buttonevent.matches is not recognized as a

I am encountering an issue with the dropdown menu that is not closing when clicking outside of the menu button. Despite having faced this problem before, I can't seem to find a solution now. Any help would be greatly appreciated as I am uncertain why ...

What is the reason behind my difficulty in opening my dialog box modally using JavaScript?

I am looking to keep a dialog open while data is being fetched from the server. Here is the code I have written: (async()=>{ document.getElementById("dialog").showModal(); if(condition1 is true){ await server_call1(); } ...

Utilize $.ajax to gracefully wait for completion without causing the UI to freeze

Consider a scenario where there is a JavaScript function that returns a boolean value: function UpdateUserInSession(target, user) { var data = { "jsonUser": JSON.stringify(user) }; $.ajax({ type: "POST", url: target, data: ...

Start from scratch when establishing the baseline for "defaults."

Struggling to reimagine the _.defaults function from underscore.js, I keep encountering this pesky error: Error message: should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' ...

Using Function Call to Generate Components in React

Being tired of repeatedly defining states to render Components based on conditions, I often find myself just wanting to display notifications or alerts. My current dilemma is figuring out how to render a component by invoking a function from within that co ...

Perform an action when the timer reaches zero

I am working with a database entry that contains the following information: { _id:"fdjshbjds564564sfsdf", shipmentCreationTime:"12:17 AM" shipmentExpiryTime:"12:32 AM" } My goal is to create a timer in the front end ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

How come my data cannot be displayed using ajax?

Here is the code snippet: var xml=new String(""); //function to send data every 5 seconds window.setInterval(function() { //code to obtain xml file alert(xml);// when I try alert my variable xml contain data ...

I wonder where the file from the HTML form download has originated

Recently, I've been experimenting with the developer tools in Chrome to observe the behavior of websites at different moments. It has proven useful in automating certain tasks that I regularly perform. Currently, my focus is on automating the process ...

Is there a way to maintain the selected position on the drop-down menu for users?

Whenever I choose an option from the drop-down field in my form, it automatically jumps back to the top of the page. Just to clarify, I have a drop-down menu at the top of the page and several input fields below. Users need to scroll down to reach the dro ...

Eliminating an SVG component from the webpage with the help of jQuery

Utilizing jQuery to insert an element into an embedded SVG can be achieved with the following code: var rect = SVG('rect'); $(rect).attr( { x: left, y: top, width: right - lef ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...

I'm struggling to concentrate and unable to type in the email field

Today while working on a website, I encountered something strange. In the footer section of the site, there is a quick contact form. However, I noticed that in Firefox, I am unable to focus on the email field. Surprisingly, this issue does not occur in Chr ...

Presenting data in various formats

I've got a JSON file with a list of data that includes months and years. I want to display all the months, but have the year only appear once in a big block area. Here's an image example: https://i.stack.imgur.com/Ps3OF.png The image demonstrates ...

Setting a default value in Vue props if it doesn't pass validation: A guide

Is it possible to assign a default value to a prop using a validator? For instance, if the current prop does not pass the validator and is less than 3, I would like to automatically set the value to 1. Here's an example: currentStep: { type ...