Reputation: 791
I'm just starting out with .NET, and am building a test application. I currently have the homepage set using a DefaultController
, and an Index()
action method. This works as expected, and the homepage is simple www.domain.com.
I have created 2 new pages (Terms and Privacy) under the same DefaultController
, using Terms()
and Privacy()
action methods.
I want to be able to browse to these with the URL as www.domain.com/terms and www.domain.com/privacy.
When i use a <li>@Html.ActionLink("Terms of Service", "Terms", "Default")</li>
it works, but it takes me to the URL at www.domain.com/Default/privacy.
Should i be creating seperate controllers for each of these pages, or am I using the @html.ActionLink
helper incorrectly? I have previously used <li><a href="~/privacy">Privacy Policy</a></li>
but I understand this isn't best practice?
Also, is there a way to force links as lowercase?
My Controller Code:
public class DefaultController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Terms()
{
return View();
}
public ActionResult Privacy()
{
return View();
}
}
Upvotes: 0
Views: 97
Reputation: 761
I believe that what you want to do is hide the controller name in the url. If that is the case, your question is answered here:
ASP.NET MVC - Removing controller name from URL
Upvotes: 1
Reputation: 1139
You can use Attribute routing to give specific routes to endpoints.
[Route("terms")]
public ActionResult Terms()
{
return View();
}
[Route("privacy")]
public ActionResult Privacy()
{
return View();
}
In your RouteConfig.cs
you must enable attribute routing with the following line of code: routes.MapMvcAttributeRoutes();
Now any urls generated with @Url.Action()
or @Html.ActionLink
should generate URLS as domain.com/privacy and domain.com/terms
Upvotes: 0
Reputation: 11971
If these were in the HomeController
I don't believe you'd have the same problem. However, I think you can get around this by using the RouteConfig
file:
routes.MapRoute(
name: "Default",
url: "{Action}/{Id}",
defaults: new { controller = "Default", Action = "Index", Id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Generic",
url: "{controller}/{Action}/{Id}",
defaults: new { Action = "Index", Id = UrlParameter.Optional }
);
Upvotes: 3