Kindzoku
Kindzoku

Reputation: 1420

Why MVC keeps route values in URL without passing them directly

I have a question. Let's say I have this routes:

/Guest/{var1}/{var2}

/Guest/{var1}/{var2}/edit

When I'm on the /Guest/123/321 page, I have a link to /Guest/123/321/edit?id=1. There is a form on the page /Guest/123/321/edit?id=1, which posts itself on the same address.

Let's say that my Actions looks like:

public ActionResult Index(int var1, int var2)
{
    /* here is some a business logic */    
    return View(model);
}

[HttpGet]
public ActionResult Edit(int id)
{
    /* here is some a business logic */
    return View(model);
}


[HttpPost]
public ActionResult Edit(EditModel model)
{
    /* here is some a business logic */
    return RedirectToAction("Index");
}

The question is why do I have URL /Guest/123/321 after RedirectToAction("Index"), after I submit the form? I mean - it's awesome. It reduces the code a lot. I just don't like to use methods, that I don't understand. :)

I always thought, that I should pass something line new { var1 = 123, var2 = 321 } to RedirectToAction in order to keep the URL.

Upvotes: 1

Views: 85

Answers (1)

NightOwl888
NightOwl888

Reputation: 56849

This is a confusing part of MVC that was previously reported as a bug1 because many people don't find this behavior to be natural. But according to Microsoft, this behavior is by design.

  1. Unfortunately, the Codeplex issue URL was taken down and is not in the Internet archive.

The behavior is that route values are reused from the current request when they are not supplied explicitly.

There are some cases where it works well, such as localizing the URL, but in other cases such as when using Areas, you have to manually clear the value in the ActionLink to be able to access the default area.

@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, null)

Upvotes: 2

Related Questions