具有相同名称的路由参数和视图模型 属性 - 意外行为
Route param and view model property with same name - unexpected behaviour
不确定这是不是一个错误,或者我错过了什么。
当我有一个路由参数 "bar" 并且在我的视图模型中有一个具有相同名称 "Bar" 的 属性 时,MVC 变得混乱并显示在 html 助手中意想不到的结果。让我们仔细看看。
(代码是自由输入的,所以它可能无法运行,但我希望它足以解决我刚刚偶然发现的问题)
让我们从以下控制器开始:
public class MyController : Controller {
...
[Route("my/route/{bar}")]
public ActionResult Foo(string bar) {
...
var viewModel = new MyViewModel() { Bar = "baz"; }
return this.View(viewModel);
}
...
}
我们将以下视图模型传递给视图:
public class MyViewModel {
...
public string Bar { get; set; }
...
}
在视图中,我们有这样的东西:
...
@Html.LabelFor(l => l.Bar)
@Html.EditorFor(m => m.Bar)
...
当我们这样喊出动作时:
@Html.ActionLink("Link", "Foo", "MyController", new { bar = "mystring" })
EditorFor 中的预期结果是 "baz"
,但不是。实际上是"mystring"
。尽管 @Model.Bar
将打印预期结果 "baz"
.
这是期望的行为还是(已知)错误?如果没有,我可以在哪里举报?
此致
这不是每个设计的错误,这就是模型绑定器在 MVC 中的工作方式:
This is by design - ModelState is the highest priority value-provider
for model properties, higher than even model itself. Without query
string parameter, ModelState does not contain value for MyProperty, so
framework uses model value.
看到这个question and answer:
不确定这是不是一个错误,或者我错过了什么。
当我有一个路由参数 "bar" 并且在我的视图模型中有一个具有相同名称 "Bar" 的 属性 时,MVC 变得混乱并显示在 html 助手中意想不到的结果。让我们仔细看看。
(代码是自由输入的,所以它可能无法运行,但我希望它足以解决我刚刚偶然发现的问题)
让我们从以下控制器开始:
public class MyController : Controller {
...
[Route("my/route/{bar}")]
public ActionResult Foo(string bar) {
...
var viewModel = new MyViewModel() { Bar = "baz"; }
return this.View(viewModel);
}
...
}
我们将以下视图模型传递给视图:
public class MyViewModel {
...
public string Bar { get; set; }
...
}
在视图中,我们有这样的东西:
...
@Html.LabelFor(l => l.Bar)
@Html.EditorFor(m => m.Bar)
...
当我们这样喊出动作时:
@Html.ActionLink("Link", "Foo", "MyController", new { bar = "mystring" })
EditorFor 中的预期结果是 "baz"
,但不是。实际上是"mystring"
。尽管 @Model.Bar
将打印预期结果 "baz"
.
这是期望的行为还是(已知)错误?如果没有,我可以在哪里举报?
此致
这不是每个设计的错误,这就是模型绑定器在 MVC 中的工作方式:
This is by design - ModelState is the highest priority value-provider for model properties, higher than even model itself. Without query string parameter, ModelState does not contain value for MyProperty, so framework uses model value.
看到这个question and answer: