简体   繁体   English

ASP NET Core 中的 asp-for 发送复选框值和 false,即使复选框被选中

[英]asp-for in ASP NET Core send checkbox value and false even if checkbox is checked

I have a simple.cshtml page:我有一个 simple.cshtml 页面:

<form asp-controller="SomeController" asp-action="SomeAction">
    @for(int i = 0; i < info.Length; i++)
    {
        <input type="checkbox" value="@info[i].Name" asp-for="Accepted[i]" checked /> <strong>@info[i].Name</strong>
        <br />
    }

    <button type="submit">Some button</button>
</form>

And when I submit this form I would like to have FormData like it:当我提交此表单时,我希望 FormData 喜欢它:

info[0]: some-data

info[1]: another-data

And I have it in my FormData, but some useless data is added to my FormData that looks like it:我在我的 FormData 中有它,但是一些无用的数据被添加到我的 FormData 中,看起来像这样:

info[0]: false

info[1]: false

What's more, its setted to false even if checkboxes are checked (when checkboxes are unchecked, they aren't contained in FormData and this useless data also isn't contained).更重要的是,即使复选框被选中,它也会设置为 false(当复选框未被选中时,它们不包含在 FormData 中,并且这些无用的数据也不包含)。

Why is this happening?为什么会这样? Can I remove it while I want to use tag helpers?我可以在我想使用标签助手时删除它吗?

In your code, You use index to bind value in Accepted , So even you don't bind any value in this index, It will also show default value.在你的代码中,你使用索引来绑定Accepted中的值,所以即使你没有在这个索引中绑定任何值,它也会显示默认值。 You can change type to string[] and use name='Accepted' to bind value directly.您可以将 type 更改为string[]并使用name='Accepted'直接绑定值。

public class ListModel
    {
        public List<string> info { get; set; } = new List<string>();
        public string[] Accepted { get; set; }
    }


<form method="post">
    @for (int i = 0; i < Model.info.Count; i++)
    {
        <input type="checkbox" value="@Model.info[i]" name="Accepted" checked /> <strong>@Model.info[i]</strong>
        <br />
    }  
    <button type="submit">Some button</button>
</form>

在此处输入图像描述

Here you can see it will not bind false value.在这里您可以看到它不会绑定 false 值。

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

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