Why MVC keeps route values in URL without passing them directly

孤人 提交于 2019-12-13 02:26:41

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/34525244/why-mvc-keeps-route-values-in-url-without-passing-them-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!