多くの場所で使用されている部分ビューにデータを渡すには、さまざまな方法があります。
すべてのモデルの基本モデルクラスを作成します。基本クラスで、部分ビューのモデルを保持するPartialModelプロパティを定義します(使用に多くの部分ビューがある場合は、それらの多くが存在する可能性があります)。これで、コントローラーアクションにPartialModelプロパティを設定できますが、コードを再利用しやすくするために、アクションメソッドが実行された直後(モデルがビューに渡される前)に部分ビューデータを挿入する独自のアクションフィルターを作成できます。
public class PartialViewModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
BaseViewModel model;
if (filterContext.Controller.ViewData.Model == null)
{
model = new BaseViewModel();
filterContext.Controller.ViewData.Model = model;
}
else
{
model = filterContext.Controller.ViewData.Model as BaseViewModel;
}
model.PartialModel = new PartialModel(...) // Partial model initialization
base.OnActionExecuted(filterContext);
}
}
次に、次のように使用できます。
[PartialViewModel]
public ActionResult Index()
{
//...
}
別のオプション:すべてのコントローラーのBaseControllerクラスを作成し、ベースコントローラーの初期化時にPartialModelを作成できます。次に、PartialModelをViewData[]ディクショナリに格納できます。ビューでViewDataディクショナリを使用するのは悪いため、HtmlHelperで次のような拡張メソッドを作成します。
public static PartialModel GetPartialModel(this HtmlHelper helper)
{
return helper.viewContext.ViewData["PartialModel"] as PartialModel
}
したがって、次の方法でモデルを取得できます。
<% Html.RenderPartial("MyPartial", Html.GetPartialModel()); %>