Home > Blockchain >  Is it possible assign the checked state to the value of the current checkbox in razor form without o
Is it possible assign the checked state to the value of the current checkbox in razor form without o

Time:12-05

I have an ASP.Net Core MVC Web Application project. I want to send the checkbox's checked state as the value to the model's related parameter on form submit. I have seen so many examples that using jquery to get/set the value of the checkbox via onchange methods.

What I wonder is that is it possible to assign the current checkbox's checked state to the value in a similar way to the code below.(it doesn't work)

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" value="(this.checked)" 

One of the simplest working examples I found is the following but it returns false if the checkbox is checked by default and its state is not changed.

<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" onchange="if(this.checked) this.value='true'; else this.value='false';" >

I know that there are many ways to achieve what I want but I want the cleanest solution.

Thanks in advance!

Edit: The structure of my razor page is as follows:

@model MyModel
<form id="UpdateForm" class="was-validated" method="post" enctype="multipart/form-data" asp-controller="ControllerName" asp-action="Update">
    <div class="modal-body">
        <div class="form-group">
            <input type="text" class="form-control" id="Name" name="DTO.Name" value="@Model.Name" required>
            <input type="checkbox" id="IsActive" name="DTO.IsActive" checked="@Model.IsActive">
        </div>
    </div>
    <div class="modal-footer">
      <button type="submit" class="btn btn-primary" data-save="modal">Update</button>
    </div>
</form>

Solution https://www.learnrazorpages.com/razor-pages/forms/checkboxes

    <input type="checkbox" data-val="true" " id="IsActive" name="DTO.IsActive" checked="@Model.IsActive" value="true"> 
    <input name="DTO.IsActive" type="hidden" value="false">

CodePudding user response:

Yes you can do it by using an inline razor statement @() It would look something like this:

<input type="checkbox" id="IsActive" name="DTO.IsActive" @(Model.IsActive ? "checked" : "") />

also you could use the Checkbox helper

@Html.CheckBoxFor(model => model.IsActive )
  • Related