Anatolii Banar
Anatolii Banar

Reputation: 43

UrlHelper in Controller Action does not build correct URL

I have an issue, when I'm trying to build the url for action in controller, the value of vm after assigning is "/". If I try to create url with other action name then everything works fine, like Url.Action("Edit", "Contact").

public class ContactController : Controller
{
    public ActionResult List()
    {
        string vm = Url.Action("Create", "Contact");     // equals "/"
        string editUrl = Url.Action("Edit", "Contact"); // all is fine

        return View("List", vm);
    }

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

    public ActionResult Edit()
    {
        return HttpNotFound();
    }
}

What's wrong with that code?

Upvotes: 4

Views: 1320

Answers (1)

Ashley Medway
Ashley Medway

Reputation: 7301

It is because your route specifies them as defaults.

Your route is:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Contact", action = "Create", id = String.Empty }, null);

Essentially, it is because you specify the default values controller = "Contact", action = "Create". When you specify these as default you are saying if the value is not provided in the URL then use these.

For examples all these URLs are the same: /, /Contact & /Contact/Create. By default MVC generates you the shortest URL.

You could either change the default values or remove them like this:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { id = String.Empty }, null);

Upvotes: 6

Related Questions