2016-06-20 4 views
0

アクションフィルタでビュー名にアクセスするためにどのようにvalidation-ASP.NET MVC: - サーバーエラーで私はモデルのアクションフィルタの下に書かれている

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'アプリケーション。

ビュー 'インデックス'またはそのマスターが見つかりませんでした。または、検索エンジンが検索された場所をサポートしていません。以下の場所が検索されました:

私の質問は - どのように私はビュー情報を渡すのですか?

+0

あなたはビュー名を取得したいです現在のアクションメソッドのために? – Shyju

+0

はいビュー名を持っています –

+0

可能な複製:[ASP .NET MVC3(ベータ版)で現在のviewName(アクション名ではない)を取得する方法](http://stackoverflow.com/q/8910219/181087) – NightOwl888

答えて

0

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イベントでこれをしたい場合、あなたはアクション名を読んで検討するかもしれないし、それを使用します(あなたのアクションメソッドがexplcitlyビュー名を指定せずにビューを返していると仮定。)

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 

} 
+0

これは目的を解決しません。このフィルタはモデル検証用です。ここで返されるビュー名は、リダイレクトされたPageの名前です。 –

+0

更新された回答を参照してください。 – Shyju

+0

'return View()'コールで別のビュー名を指定しています –

関連する問題