Retrieve the current view name in ASP.NET MVC?

后端 未结 10 895
谎友^
谎友^ 2020-11-28 09:37

I have a partial view (control) that\'s used across several view pages, and I need to pass the name of the current view back to the controller - so if there\'s e.g. validati

10条回答
  •  天涯浪人
    2020-11-28 10:18

    Just wrote a blog thingy about this

    http://www.antix.co.uk/A-Developers-Blog/Targeting-Pages-with-CSS-in-ASP.NET-MVC

      /// 
      /// Get a string from the route data
      /// 
      public static string RouteString(
          this ViewContext context, string template) {
    
       foreach (var value in context.RouteData.Values) {
    
        template = template.Replace(string.Format("{{{0}}}",
                value.Key.ToLower()),
                value.Value == null
                    ? string.Empty
                    : value.Value.ToString().ToLower());
       }
    
       return template;
      }
    

    usage

    ">
    

    EDIT : Yes this is not going to give you the view name as the first comment states, it gives you the controller and action. But leaving it here as its valuable to know that it doesn't.

提交回复
热议问题