简体   繁体   English

发送数据时,控制器中的模型中的布尔字段未更新

[英]boolean fields in a model are not being updated in the controller when the data is sent

I had a view without a model in Razor with a form and some inputs and checkboxes, in the controler I'am waiting for a Model to be mapped with the sended data and the input are already well-mapped but the checkboxes not. 我有一个视图,在Razor中没有模型,但有一个窗体以及一些输入和复选框,在控制器中,我正在等待将模型与发送的数据映射,并且输入已经被很好地映射,但是复选框没有。

I saw the Network Tab in the DevTool and the checkboxes fields are being sent but with an empty data. 我在DevTool中看到了“网络”选项卡,正在发送复选框字段,但数据为空。

[HttpPost]
public async Task<IActionResult> EditLink(LinkDto editedLinkDto)
{
    // the text fields of editedLinkDto are correctly received, but the booleans (the ckeckboxes) not...
    ...
}

The view: 风景:

...
<form asp-area="Admin" asp-controller="Features" asp-action="EditLink" method="post">
    <input name="LinkName">
    <input name="LinkUrl">

    <input name="BlankTarget" value="true" type="checkbox" />
    <input name="AllowEdit" value="true" type="checkbox" />

    ...
</form>
...

PD: The name attributes in the fields has the same name that the attributes of the dto I'm receiving in the dto PD:字段中的名称属性与我在dto中接收到的dto属性的名称相同

As I said before, the LinkName and the LinkUrl fields are being sent but the BlankTarget and AllowEdit fields always are false in the controller and in the DevTool I'm seeing that they are being sent with an empty value. 如前所述,正在发送LinkName和LinkUrl字段,但在控制器中以及在DevTool中,BlankTarget和AllowEdit字段始终为false,我看到它们以空值发送。

If not using asp-for attribute , you can modify your codes to add a hidden field. 如果不使用asp-for属性,则可以修改代码以添加隐藏字段。 It will be submitted regardless whether the checkbox is checked or not. 无论是否选中该复选框,都将提交。 If the checkbox is checked, the posted value will be true/false . 如果选中此复选框,则发布的值为true/false The model binder will correctly extract true from the value. 模型绑定器将从值中正确提取true。 Otherwise it will be false : 否则它将是错误的:

<input type="checkbox" data-val="true" id="BlankTarget" name="BlankTarget" value="true" checked>
<label for="BlankTarget">Name</label>
<input name="BlankTarget" type="hidden" value="false">

But it is recommend to use Tag Helpers in asp.net core : 但是建议在asp.net core中使用Tag Helpers:

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-2.2 https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-2.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM