Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert Web.Http.Results.JsonResult to Web.Mvc.JsonResult

I've set up this test method on a controller to strip out any complication to it. Based off of all the results I've found from searching this should work. I'm not sure what I'm missing here.

public JsonResult test() 
{
    return Json(new { id = 1 });
}

This is the error I get.

Cannot implicitly convert type 'System.Web.Http.Results.JsonResult' to 'System.Web.Mvc.JsonResult'

like image 448
Jhorra Avatar asked Jun 06 '14 06:06

Jhorra


4 Answers

you should return a JsonResult instead of just Json

 public JsonResult test() 
    {
        var result = new JsonResult();
        result.Data = new
        {
             id = 1
         };
        result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        return result;
    }
like image 125
xei2k Avatar answered Sep 29 '22 16:09

xei2k


Try the following:

public System.Web.Http.Results.JsonResult test() 
{
    return Json(new { id = 1 });
}

It seems that Json does not generate a System.Web.Mvc.JsonResult which is expected as you are probably using System.Web.Mvc; but a System.Web.Http.Results.JsonResult.
The more generic one should also work:

public ActionResult test() 
{
    return Json(new { id = 1 });
}

NOTE:
In my MVC controllers the Json method does return a System.Web.Mvc.JsonResult. Are you inheriting from the default System.Web.Mvc.Controller?

like image 33
Christoph Fink Avatar answered Sep 29 '22 16:09

Christoph Fink


Try

return Json(new { id = 1 }, JsonRequestBehavior.AllowGet);

like image 42
Arijit Mukherjee Avatar answered Sep 29 '22 15:09

Arijit Mukherjee


You need to return the data through a model class rather than an anonymous class. Like:

public System.Web.Http.Results.JsonResult<modelClass> test(){
        return Json(new modelClass(){ id=1 });
}
like image 20
irtaza Avatar answered Sep 29 '22 14:09

irtaza