0

What I am trying to do is to get a specific person from the persons list. My Post works fine and I get the person I am looking for as "chosenPerson" in the controller. After that I want to get that person as a complex Json object for use in my view. But something in the serializer.Serialize(chosenPerson) doesn't seem to work and I get an exception on that line saying:

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

Additional information: Exception has been thrown by the target of an invocation."

JS in 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/');

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);
}
Muhammed Shevil KP
  • 1,406
  • 1
  • 15
  • 21
  • pretty sure you can just do `return Json(chosenPerson...` and MVC will serialise it automatically for you. You might have to put `.toList()` after the where as well, to force it to actually run the EF query before it attempts the serialisation. – ADyson Feb 14 '17 at 10:07
  • @ADyson I tried doing this and got the following error: "Self referencing loop detected for property 'Person'" – ForTheLoveOfCode Feb 15 '17 at 09:32
  • does the chosenPerson object have a property called Person which is also of the same type? See the potential solutions here: http://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type – ADyson Feb 15 '17 at 09:42
  • @ADyson Thank you, ignoring the loop worked for me. How do I check in my JS wether the GET was successful? The object that is returned in the controller is populated but what I get in the view seems to be an empty object. – ForTheLoveOfCode Feb 15 '17 at 12:22
  • watch the network tab in your browser. You should see the ajax request and can view the HTTP code returned, and see both the request and response that were sent. Your structure is wrong though.. You are sending a POST, but not acting on the response. Instead you make a separate GET (which is a totally different request - you would have to provide the email address again to do this) - but your action method does not allow GET, anyway (due to the [HttpPost] attribute). You need to handle the "success" callback of your POST request. Two separate requests for this makes no sense. – ADyson Feb 15 '17 at 13:17

1 Answers1

0

You have a few issues with code. I would advise using Newtonsoft.Json to serialize the Json. Note I have removed the [HttpPost]. Change your controller to:

public JsonResult ReturnPerson(string emailUnique)
{
    var db = new CvAdminContext();
    var chosenPerson= db.Persons.Where(p => p.Email == emailUnique).ToList();

    return Json(JsonConvert.SerializeObject(chosenPerson), JsonRequestBehavior.AllowGet);

}

Then from your client side you can use:

var email = "whatever@whatever.com";
// you could also use var email = @Model.Email; if view is strongly typed.

var chosenPerson = $.getJSON('/Home/ReturnPerson?emailunique=' + email, function(data) {
    console.log(data);
});
James P
  • 2,061
  • 2
  • 19
  • 28
  • I attempted this and got the following error: "There is already an open DataReader associated with this Command which must be closed first." – ForTheLoveOfCode Feb 15 '17 at 09:28
  • As above either add `.ToList()` to the linq query or add `MultipleActiveResultSets=true;` to your connection string. – James P Feb 15 '17 at 11:08
  • The return statement now works and a populated object is returned. However what is received, if anything at all, seems to be an empty object. How do I check to see if the GET was successful? – ForTheLoveOfCode Feb 15 '17 at 12:28
  • Put a break point on the linq query to see whats returned from db. – James P Feb 15 '17 at 13:21
  • Sorry for the late response. A version of this worked for me: `string json = JsonConvert.SerializeObject(persondto, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return Json(json);` – ForTheLoveOfCode Mar 15 '17 at 07:55