为什么MVC将路由值保留在URL中而不直接传递它们

为什么MVC将路由值保留在URL中而不直接传递它们

本文介绍了为什么MVC将路由值保留在URL中而不直接传递它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题.假设我有以下路线:

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

/来宾/{var1}/{var2}/edit

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

当我进入/Guest/123/321页面时,我具有指向/Guest/123/321/edit?id=1的链接./Guest/123/321/edit?id=1页上有一个表单,该表单将自己张贴在相同的地址上.

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.

假设我的操作如下:

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

问题是,提交表单后,为什么在RedirectToAction("Index")之后有URL /Guest/123/321?我的意思是-太棒了.它大大减少了代码.我只是不喜欢使用我不了解的方法. :)

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. :)

我一直认为,我应该在{ var1 = 123, var2 = 321 }的新行中添加一些内容,以保留URL.

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

推荐答案

这是MVC的一个令人困惑的部分,以前被报告为bug ,因为许多人并不认为这种行为是有天赋的人.但是据微软称,这种行为是设计使然.

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

  1. 不幸的是,Codeplex问题URL已被删除,并且不在Internet存档中.

行为是当未明确提供路由值时,它们会从当前请求中重新使用.

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

在某些情况下它可以很好地工作,例如,但在其他情况下,例如,您必须手动清除ActionLink中的值才能访问默认区域.

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)

这篇关于为什么MVC将路由值保留在URL中而不直接传递它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 10:49