2016-07-25 100 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 }); 
     } 
    } 
相關問題