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.
Values["controller"]. ToString(); And this will return the name of the controller requested in the URL: var requestedController = HttpContext.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With