ASP .Net MVC C# 中 ChildActionOnly 特性有哪些用途?


子操作只能透過子請求訪問。它不會響應 URL 請求。如果嘗試這樣做,將引發一條執行時錯誤,說明 - 子操作只能透過子請求訪問。可以使用操作() 和 RenderAction() html 幫助程式,透過從檢視發出子請求來呼叫子操作方法。

子操作方法與 NonAction 方法不同,因為 NonAction 方法不能使用 Action() 或 RenderAction() 幫助程式呼叫。

下面是我們嘗試使用 URL 呼叫時出現的子操作錯誤。

控制器

示例

using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public ActionResult Index(){
         return View();
      }
      [ChildActionOnly]
      public ActionResult Countries(List<string> countries){
         return View(countries);
      }
   }
}

索引檢視

@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
@Html.Action("Countries", new { countries = new List<string>() { "USA", "UK",
"India", "Australia" } })

國家檢視

@model List<string>
@foreach (string country in Model){
   <ul>
      <li>
         <b>
            @country
         </b>
      </li>
   </ul>
}

輸出

也可以使用“RenderAction()”HTML 幫助程式呼叫子操作,如下所示。

@{
   Html.RenderAction("Countries", new { countryData = new List<string>() {
   "USA", "UK", "India", "Australia" } });
}

更新於:2020 年 9 月 24 日

945 次觀看

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.