theJ
theJ

Reputation: 395

Checkbox status in Razor pages

I am using MVC with Entity Framework and I can create groups which may or may not belong to a client. The way I have done this is added a checkbox if it is empty (false) the ClientId equals null. However, if it is checked (true) I would like the ClientId to equal a ViewBag I have set up in the controller.

<div class="form-group">
   <label asp-for="isClient">Client Specific
        <input type="checkbox" asp-for="isClient"/>
   </label>
</div>
<div class="form-group" id="ClientId" style="display:none;">
    <label asp-for="ClientId" class="control-label">Client Name</label>
    <input asp-for="ClientId" class="form-control" value="">
    <span asp-validation-for="ClientId" class="text-danger"></span>
</div>

Is there a way I can check the status of the CheckBox inside the Razor page and set the value of the ClientId?

I was thinking of doing something like below then returning the value to the value of the ClientId.

@if (Model.isClient == true)
{
    var value = ViewBag.ClientId;
}
else
{
    var value = "";
}

Upvotes: 0

Views: 5016

Answers (2)

Kamil Folwarczny
Kamil Folwarczny

Reputation: 591

Would have reply in comments but i dont have enought reputation for that. Thats why answer.

Since everything what is happening on razor page is happening on server, you can do this in your View Model. If you dont want to do this in View Model or you are sending directly Data Access Model from your action. You can modify that Data Access Model in your action.

However if you want to do this on razor page for what ever reason. Then place this line before your html elements:

@{ Model.ClientId = Model.isClient == true ? ViewBag.ClientId : ""; }

Assuming that ClientId is part of model.

Hope it helps.

Upvotes: 0

poke
poke

Reputation: 387825

Since you can change the checked state of the checkbox on the client side, if that would have to change the value of the input field, then that would require some client side logic using JavaScript.

A much more flexible way would be to simply pass both the checkbox value and the client id back to the server and then have the logic run there whether or not the client id should be used.

So your UI would look like this:

<input type="checkbox" asp-for="IsClient" />

<!-- use a hidden input field to just transfer data -->
<input type="hidden" asp-for="ClientId" value="@ViewBag.ClientId" />

Assuming that your model has both an IsClient and a ClientId property.

Then in your form submit handler, you simply check whether the IsClient is set. If yes, you can use the ClientId, otherwise just discard it:

if (!model.IsClient)
{
    // clearing the client id
    model.ClientId = "";
}

Of course, if you can determine the ClientId on the form submit handler, you can also just calculate it there, instead of having to put it into the ViewBag when the form is rendered.

Upvotes: 1

Related Questions