Binding a checkbox with Viewmodel without the use of Razor (Asp.net core MVC)

Asked

Viewed 268 times

0

I’m having problems with Razor... I need to create a checkbox field and Binding with my viewModel using pure html. Only I’m not being able to do the Binding correctly with the bool property and even if I select or not the checkbox, when I do Submit, it is always false the value... How do I make Binding correctly? (fields are being created dynamically...)

<div class="checkbox-custom checkbox-default">
    <input type="checkbox" name="PessoasContatosViewModel[@i].ContatoPrincipal" class="ckb-contatoPrincipal" autocomplete="off" />
    <label asp-for="PessoasContatosViewModel[i].ContatoPrincipal" class="ckb-contatoPrincipal">Contato Principal</label>
</div>

I was able to solve the problem by validating the checked property, but it is correct?

<div class="col-md-2">
    <label class="control-label">&nbsp;</label>
    <div class="checkbox-custom checkbox-default">
        <input type="checkbox" name="PessoasContatosViewModel[@i].ContatoPrincipal" value="true" checked ="@(Model.PessoasContatosViewModel[i].ContatoPrincipal)" class="ckb-contatoPrincipal" autocomplete="off" />
        <label asp-for="PessoasContatosViewModel[i].ContatoPrincipal" class="ckb-contatoPrincipal">Contato Principal</label>
    </div>
</div>
  • Dude, try to set a default value for it, value="true" checked, so, if there is any change it will identify and send to the controller. Take the test and let me know.

  • Hello @Victorlaio! I added value="true" and solved the Submit part. The checked is getting in the way, because when it returns the template to the view, it is always true, regardless of whether the bool property is true or false. What to do, sir

  • @Victorlaio, I updated my post with a possible solution in which it worked, but I don’t know if it would be the right way. I set value="true" and used the Razor to validate the checked, because when receiving the bank registration, it right arrow... What do you think?

  • I think viable, although you did not want to use the Razor but ended up working! Enjoy! Hehe. I will post the answer then.

1 answer

0


You should put a property for it checked or not, because it identifies the changes as if it were an event "on".

Add this part to your checkbox:

value="true" checked

As you mentioned, you can try using Razor to define whether it is actually checked or not leaving in the following way:

checked ="@(Model.PessoasContatosViewModel[i].ContatoPrincipal)"

Any questions, and if I can be of any further help, just let me know! :)

  • Thank you @Victor Laio! Your help was very important. Hug! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.