ASP.NET Core:asp- *属性在模型上使用请求有效负载吗? [英] ASP.NET Core: asp-* attributes use request payload over model?

查看:82
本文介绍了ASP.NET Core:asp- *属性在模型上使用请求有效负载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在ASP.NET Core中, asp-* 属性中的值(例如 asp-for )从模型之前的请求有效负载中获取。示例:

It seems that in ASP.NET Core, the value in asp-* attributes (e.g. asp-for) is taken from the request payload before the model. Example:

发布此值:

MyProperty="User entered value."

此操作:

[HttpPost]
public IActionResult Foo(MyModel m)
{
    m.MyProperty = "Change it to this!";
    return View();
}

或此操作

[HttpPost]
public IActionResult Foo(MyModel m)
{
    m.MyProperty = "Change it to this!";
    return View(m);
}

视图会显示以下内容:

<input asp-for="MyProperty" />

表单输入中的值是用户输入的值。而不是将其更改为此!

The value in the form input is User entered value. and not Change it to this!.

首先,我很惊讶我们没有无需将模型传递给视图即可使用。其次,令我震惊的是,请求有效负载优先于传递到视图中的模型。有人知道此设计决定的依据是什么?使用 asp-for 属性时,是否有方法可以覆盖用户输入的值?

First of all, I'm surprised that we don't need to pass the model to the view and it works. Secondly, I'm shocked that the request payload takes precedence over the model that's passed into the view. Anyone know what the rationale is for this design decision? Is there a way to override the user entered value when using asp-for attributes?

推荐答案

我相信这是预期的行为/设计使然。因为当您提交表单时,表单数据将存储到ModelState词典中,而当razor呈现表单元素时,它将使用Model状态词典中的值。这就是为什么即使不将视图模型的对象传递给 View()方法也看到表单元素值的原因。

I believe this is the expected behavior/by design. Because when you submit the form, the form data will be stored to ModelState dictionary and when razor renders your form elements, it will use the values from the Model state dictionary. That is why you are seeing your form element values even when you are not passing an object of your view model to the View() method.

如果要更新输入值,则需要明确清除Model状态字典。您可以使用 ModelState.Clear()方法来实现。

If you want to update the input values, you need to explcitly clear the Model state dictionary. You can use ModelState.Clear() method to do so.

[HttpPost]
public IActionResult Create(YourviewModel model)
{       
    ModelState.Clear();
    model.YourProperty = "New Value";
    return View(model);
}

使用Model状态字典来渲染表单元素值的原因是为了支持例如,在发生验证错误时在表单中显示以前提交的值。

The reason it uses Model state dictionary to render the form element values is to support use cases like, showing the previously submitted values in the form when there is a validation error occurs.

编辑:我找到了指向aspnet mvc的官方github回购,其中这已由Eilon(asp。网络团队成员)

EDIT : I found a link to the official github repo of aspnet mvc where this is confirmed by Eilon (asp.net team member)

https://github.com/aspnet/Mvc/issues/4486#issuecomment-210603605

这篇关于ASP.NET Core:asp- *属性在模型上使用请求有效负载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆