Home > Enterprise >  asp-for in ASP NET Core send checkbox value and false even if checkbox is checked
asp-for in ASP NET Core send checkbox value and false even if checkbox is checked

Time:12-20

I have a simple .cshtml page:

<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:

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:

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).

Why is this happening? Can I remove it while I want to use tag helpers?

CodePudding user response:

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. You can change type to string[] and use name='Accepted' to bind value directly.

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>

enter image description here

Here you can see it will not bind false value.

  • Related