Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current controller in view

People also ask

How do I find my current controller?

Get controller name In preceding code, we use the ViewContext object to access the RouteData of the current request. After that, we use the Values property to access the current routing path values. By passing the controller key to the Values property we can get the current controller name.

How do I find my controller name in razor view?

Values["controller"]. ToString(); And this will return the name of the controller requested in the URL: var requestedController = HttpContext.

How to get controller name Laravel?

If you require to get current controller name in your view file or in your middleware or your serviceprovider etc. you can get your controller details from current route like UserController, HomeController ect. you can also get full path of controller file.

Which code statement is used to create a hyperlink to an action in a controller in an area?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.


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()');

I do it like this:

@ViewContext.RouteData.Values["controller"]

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"; } 
    }

Other way to get current Controller name in View

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

Just use:

ViewContext.Controller.GetType().Name

This will give you the whole Controller's Name


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