Jonathan Wood Jonathan Wood - 1 month ago 21
Ajax Question

How to return JsonResult

I'm having trouble writing this AJAX method.

I want to return a

JsonResult
. (Seems like the logical thing to do.) All the examples I could find use
Json()
to convert the result to a
JsonResult
.

[HttpPost]
public JsonResult GetScoreResults(string userId, int chapterId)
{
return new Json(ChapterScoreResultsModel.Create(DbContext, userId, chapterId));
}


But when I try this:


The type or namespace name 'Json' could not be found (are you missing a using directive or an assembly reference?)


However, I can't find this symbol anywhere and all the articles I found that used it didn't seem to do anything special. I did find the symbol in the namespace
System.Web.Helpers
but when I add a
using
for that, I get the error:


Cannot create an instance of the static class 'Json'


What is the current way to return a
JsonResult
from an AJAX method?

Answer Source

The Controller class has a Json method. Invoking it returns a JsonResult. Note that it's method, not a constructor. You do not put the new keyword in front of the method call.

return Json(ChapterScoreResultsModel.Create(DbContext, userId, chapterId));