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

不问归期 提交于 2019-12-22 04:40:23

问题


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'


回答1:


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;
    }



回答2:


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?




回答3:


Try

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




回答4:


In MVC JsonResult is inherited from ActionResult which is in namespace System.Web.Mvc

thats why you should make the Reference to System.Web.Mvc.JsonResult as::

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



回答5:


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 });
}



回答6:


Put this in your Using:

using System.Web.Http.Results;

Then Your Action:

public JsonResult<YourClass> Get(string Search)
        {
           var Search = Search
           return Json(Search);
        }


来源:https://stackoverflow.com/questions/24075409/cannot-implicitly-convert-web-http-results-jsonresult-to-web-mvc-jsonresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!