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

查看:23
本文介绍了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();
}

OR 这个动作

[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 呈现您的表单元素时,它将使用模型状态字典中的值.这就是为什么即使您没有将视图模型的对象传递给 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.

如果要更新输入值,则需要明确清除模型状态字典.您可以使用 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);
}

它使用模型状态字典来呈现表单元素值的原因是支持用例,例如,在发生验证错误时在表单中显示先前提交的值.

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.net 团队成员)确认

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天全站免登陆