Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the controller's name hyphen "-" separated?

I am able to use the

[ActionName("My-Action-Name")]
public ActionResult MyActionName()
{
    return View();
}

But I am facing a problem in changing the controller's Name. Is there some annotation available to make controller name hyphen (-) separated in MVC 4?

Somewhat like this:

[ControllerName("My-Controller-Name")]
public class MyControllerName : Controller
{

}
like image 640
Shan k Avatar asked Oct 03 '14 08:10

Shan k


2 Answers

Here is a good answer:

Add custom route handler (in replace part choose how you want to handle hyphens):

public class HyphenatedRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "");
        requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "");
        return base.GetHttpHandler(requestContext);
    }
}

and use it in your RouteConfig

routes.Add(
        new Route("{controller}/{action}/{id}",
            new RouteValueDictionary(
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
                new HyphenatedRouteHandler())
        );
like image 168
aleha Avatar answered Nov 15 '22 18:11

aleha


You can use Attribute Routing.

It comes in MVC 5 as well.

You can find some examples below.

http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

[RoutePrefix("Book-Reviews")]
public class ReviewsController : Controller
{
    // eg.: /reviews
    [Route]
    public ActionResult Index() { ... }
    // eg.: /reviews/5
    [Route("{reviewId}")]
    public ActionResult Show(int reviewId) { ... }
    // eg.: /reviews/5/edit
    [Route("{reviewId}/edit")]
    public ActionResult Edit(int reviewId) { ... }
}
like image 20
DarthVader Avatar answered Nov 15 '22 18:11

DarthVader