Get current controller in view

后端 未结 7 851
北荒
北荒 2020-12-04 11:55

I have a View - _Edit which lives in News M/V/C.

I reuse the V/M via the CategoryController as:

r         


        
相关标签:
7条回答
  • 2020-12-04 12:28

    I have put this in my partial view:

    @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
    

    in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.

    So use this alert instead:

    alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
    
    0 讨论(0)
  • 2020-12-04 12:28

    Create base class for all controllers and put here name attribute:

    public abstract class MyBaseController : Controller
    {
        public abstract string Name { get; }
    }
    

    In view

    @{
        var controller = ViewContext.Controller as MyBaseController;
        if (controller != null)
        {
           @controller.Name
        }
    }
    

    Controller example

     public class SampleController: MyBaseController 
        { 
          public override string Name { get { return "Sample"; } 
        }
    
    0 讨论(0)
  • 2020-12-04 12:28

    You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder.

    0 讨论(0)
  • 2020-12-04 12:37

    You can use any of the below code to get the controller name

    @HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
    

    If you are using MVC 3 you can use

    @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
    
    0 讨论(0)
  • 2020-12-04 12:41

    I do it like this, but perhaps it's only ASP.NET MVC 4

    @ViewContext.RouteData.Values["controller"]
    
    0 讨论(0)
  • 2020-12-04 12:43

    Other way to get current Controller name in View

    @ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
    
    0 讨论(0)
提交回复
热议问题