You need to use Attribute Routing, a feature introduced in MVC 5.
Based on your example you should edit your controller as follows:
[RoutePrefix("example-name")]
public class example_nameController : Controller
{
// Route: example-name/Index
[Route]
public ActionResult Index()
{
return View();
}
// Route: example-name/Contact
[Route]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
Using the RoutePrefix
attribute on top of your controller will allow you to define the route on the entire controller.
As said before, this feature is available natively in MVC 5, if you are using a previous version of MVC you need to add the following NuGet package: AttributeRouting and add the following using in your controller:
using AttributeRouting;
using AttributeRouting.Web.Mvc;
If you have another controller called
example_name2Controller
and you want to add an hyperlink that link to it you can easily do it as follows:
@Html.ActionLink("Go to example-name2", "Index", "example_name2");
You don't need to call an action that will redirect to the example_name2Controller
, but if you need to do it in other occasions, you can do it like this:
public ActionResult RedirectToExample_Name2Controller()
{
return RedirectToAction("Index", "example_name2");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…