2016-07-25 318 views
13

在我的ASP.NET核心(.NET Framework)项目中,我在以下控制器操作方法中遇到了以上错误。我可能错过了什么?或者,是否有任何变通?:ASP.NET核心 - 名称'JsonRequestBehavior'在当前上下文中不存在

public class ClientController : Controller 
    { 
     public ActionResult CountryLookup() 
     { 
     var countries = new List<SearchTypeAheadEntity> 
      { 
       new SearchTypeAheadEntity {ShortCode = "US", Name = "United States"}, 
       new SearchTypeAheadEntity {ShortCode = "CA", Name = "Canada} 
      }; 

     return Json(countries, JsonRequestBehavior.AllowGet); 
     } 
    } 

UPDATE

请注意,从@NateBarbettini如下因素的意见如下:

  1. JsonRequestBehavior已经在ASP.NET 1.0的核心被否决。
  2. 在接受的来自@Miguel的回应中,动作方法does notreturn type具体需要是JsonResult类型。 ActionResult或IActionResult也可以。
+0

看为[JsonRequestBehavior]的文件(https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior(v = vs.118)的.aspx)。 __Namespace__是您在文件顶部的'using'语句之后需要放置的内容,__Assembly__是您必须包含的对项目的引用。 –

+0

@SamIam谢谢你的MSDN链接。我正在使用ASP.NET Core 1.0(.NET Framework)项目模板,当我搜索引用 - >添加对话框时,似乎没有System.Web.MVC程序集可用。任何建议或解决方法? – nam

+2

@nam AFAIK,'JsonRequestBehavior'在ASP.NET Core 1.0中已被弃用。 –

回答

15

返回JSON格式的数据:

public class ClientController : Controller 
{ 
    public JsonResult CountryLookup() 
    { 
     var countries = new List<SearchTypeAheadEntity> 
     { 
      new SearchTypeAheadEntity {ShortCode = "US", Name = "United States"}, 
      new SearchTypeAheadEntity {ShortCode = "CA", Name = "Canada} 
     }; 

     return Json(countries); 
    } 
} 
+2

它并不特别需要具有返回类型的'JsonResult'。 'ActionResult'或'IActionResult'也可以。 –

+0

@NateBarbettini谢谢。我在文章的另一个“更新”部分添加了您的评论。 – nam

0

有时你需要如下返回的消息早在JSON,只需使用JSON结果,不需要jsonrequestbehavior更多,下面简单的代码来使用

public ActionResult DeleteSelected([FromBody]List<string> ids) 
    { 
     try 
     { 
      if (ids != null && ids.Count > 0) 
      { 
       foreach (var id in ids) 
       { 
        bool done = new tblCodesVM().Delete(Convert.ToInt32(id)); 

       } 
       return Json(new { success = true, responseText = "Deleted Scussefully" }); 

      } 
      return Json(new { success = false, responseText = "Nothing Selected" }); 
     } 
     catch (Exception dex) 
     { 

      return Json(new { success = false, responseText = dex.Message }); 
     } 
    } 
相关问题