Reputation: 1148
Currently I am using the default route but I need a route that works like this:
localhost/Admin/Users/Index
localhost/Admin/Users/Add
localhost/Admin/Users/Delete
Where index add and delete are views with controllers in the AdminController.cs
The current structure everywhere else is fine, as it doesn't require multiple subdirectories.
Currently I have the the file I need to start with in:
{Project}/Views/Admin/Users/Index.cshtml
How would I create this route and how do I apply it to the controller?
Am I approaching this incorrectly?
Upvotes: 0
Views: 104
Reputation: 12305
This can be easily resolved using Route attributes
, like:
[Route("Admin/Users/Edit/{id?}")]
public ActionResult TestView(string id)
{
if (!string.IsNullOrEmpty(id))
{
return View(“OneUser”, GetUser(id));
}
return View(“AlUsers”, GetUsers());
}
Upvotes: 1
Reputation: 15982
You can register another route specifying the route path and the controller in RegisterRoutes
:
routes.MapRoute(
name: "Admin",
url: "{controller}/Users/{action}/{id}",
defaults: new { id = UrlParameter.Optional },
constraints: new { controller = "Admin" }
);
To handle your directory structure you need to extend the default view engine to add the new view paths:
public class ExtendedRazorViewEngine : RazorViewEngine
{
public ExtendedRazorViewEngine()
{
List<string> existingPaths = new List<string>(ViewLocationFormats);
existingPaths.Add("~/Views/Admin/Users/{0}.cshtml");
ViewLocationFormats = existingPaths.ToArray();
}
}
And register the engine in Application_Start
:
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ExtendedRazorViewEngine engine = new ExtendedRazorViewEngine();
ViewEngines.Engines.Add(engine);
...
}
Upvotes: 0