Get current controller in view
asp.net Mvc-3asp.net Mvc-3 Problem Overview
I have a View - _Edit
which lives in News M/V/C
.
I reuse the V/M
via the CategoryController
as:
return PartialView("/Views/News/_Edit.cshtml", model);
How from within the View - _Edit
can I alert the controller name?
When I:
alert('@ViewContext. RouteData.Values["controller"].ToString()');
The Value is: News
However, the URL is: /Category/foobar
Is there a way to get the value 'Category'
to alert? thanks
asp.net Mvc-3 Solutions
Solution 1 - asp.net Mvc-3
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()');
Solution 2 - asp.net Mvc-3
I do it like this:
@ViewContext.RouteData.Values["controller"]
Solution 3 - asp.net Mvc-3
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"; }
}
Solution 4 - asp.net Mvc-3
Other way to get current Controller name in View
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
Solution 5 - asp.net Mvc-3
Just use:
ViewContext.Controller.GetType().Name
This will give you the whole Controller's Name
Solution 6 - asp.net Mvc-3
You are still in the context of your CategoryController
even though you're loading a PartialView
from your Views/News
folder.
Solution 7 - asp.net Mvc-3
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
Solution 8 - asp.net Mvc-3
For anyone looking for this nowadays (latest versions) of ASP.NET Core MVC
, you can use:
@Context.Request.RouteValues["controller"].ToString()