簡體   English   中英

ASP.NET MVC:如何在操作篩選器中訪問視圖名稱

[英]ASP.NET MVC: How to access View Name in a Action Filter

我在下面編寫了用於模型驗證的動作過濾器-

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var viewData = filterContext.Controller.ViewData;
        var viewNme = filterContext.Controller;
        if (!viewData.ModelState.IsValid)
        {
            filterContext.Result = new ViewResult
            {
                ViewData = viewData,
                ViewName = "Test"

            };
        }
        base.OnActionExecuting(filterContext);
    }

如果我不傳遞ViewName = "WhitePaper" ,則失敗,並顯示以下消息-'/Travelers.eBusiness.Travelers.Web'應用程序中的服務器錯誤。

找不到視圖“索引”或其主視圖,或者沒有視圖引擎支持搜索到的位置。 搜索了以下位置:

我的問題是-如何傳遞視圖信息?

您可以在OnActionExecuted事件上獲取結果的視圖名稱。

這應該為您提供視圖名稱。

public override void OnActionExecuted(ActionExecutedContext filterContext)
{       
    var viewData = filterContext.Controller.ViewData;
    var view = filterContext.Result as ViewResultBase;
    if (view != null)
    {
        string viewName = view.ViewName;
        // If we did not explicitly specify the view name in View() method,
        // it will be same as the action name. So let's get that.
        if (String.IsNullOrEmpty(viewName))
        {
            viewName = filterContext.ActionDescriptor.ActionName;
        }
        // Do something with the viewName now

    }
}

執行操作方法后, filterContext.Controller.ViewData將可用(不為null)。 但是,如果您希望在OnActionExecuting事件中使用此方法,則可以考慮讀取操作名稱並使用該名稱(假設您的操作方法正在返回視圖而未明確指定視圖名稱。)

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   var actionMethodName = filterContext.ActionDescriptor.ActionName;
   // This will be same as your view name if you are not explicitly
   // specifying a different view name in the `return View()` call

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM