Search code examples
asp.net-mvchtml-helperhtml.actionlink

MVC ActionLink advice


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();
    }
}

Solution

  • 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 }
    );