Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MVC 4 ControllerName attribute

I'm working on providing friendly names for my MVC 4 controllers and I want to do something like the [ActionName="My-Friendly-Name"] style, but for the whole controller.

I couldn't find any information about such an attribute, so how would I go about doing that? Also, will I need to add a new MapRoute to handle it?

EDIT:

For example, I'd like to route the following url:

 http://mysite.com/my-reports/Details/5

be routed to the following controller:

[ControllerClass="my-reports"]  // This attribute is made up.  I'd like to know how to make this functionality
public class ReportsController : Controller
{
    //
    // GET: /Reports/

    public ActionResult Index()
    {
        return View();
    }

    public ViewResult Details(int id)
    {
        Report report = db.Reports.Single(g => g.Id == id);
        return View(report);
    }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Report item)
    {
        try
        {
            if (ModelState.IsValid)
            {
                item.Id = Guid.NewGuid();
                _context.Reports.AddObject(item);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(item);
        }
        catch (Exception)
        {
            return View(item);
        }
    }

}

like image 700
joe_coolish Avatar asked Sep 22 '12 01:09

joe_coolish


Video Answer


2 Answers

Add a custom route that will match your specific name:

routes.MapRoute(
    "MyCustomRoute",
    "My-Friendly-Name/{action}/{id}",
    new { controller = "ReportsController", action = "Index", id = "" }
);

Now every url that contains "My-Friendly-Name" for the controller will use your new route.

like image 79
smirne Avatar answered Sep 22 '22 14:09

smirne


Checkout this post, particularly where it talks about Route formatting.

like image 38
Max Toro Avatar answered Sep 21 '22 14:09

Max Toro