Sumedha Vangury
Sumedha Vangury

Reputation: 673

Disabling checkbox in mvc does not submit values to database

Is it that if a checkbox is disabled, the value does not get submitted to the database? I have disabled a checkbox so that even if the user does not enter any values in the rest of the form, atleast one value will be submitted. But when I click on the submit button there is no entry in the database. Please Help

<table class="table-bordered">
<tr>
    <td colspan="2">
        @Html.CheckBoxFor(m => m.isUsed, new { @disabled="disabled"})
    </td>
</tr>
<tr>
    <td>
         @Html.TextBoxFor(m => m.FirstName, @Model.isUsed ? (object)new { @class = "form-control" } : new { @class = "form-control", @disabled = "disabled" })
        @Html.ValidationMessageFor(m => m.FirstName)
    </td>
</tr>

Upvotes: 2

Views: 3723

Answers (3)

macness
macness

Reputation: 11

Another way to handle this without adding extra overhead to the front end page is to just use a default value of false/0 for the corresponding backend parameter. That way you don't care if the value was posted or not (depending on your app architecture of course).

i.e. If it's unchecked (and thus not posted) it ends up false at the backend. If it was checked and is posted, it overrides the false/0 value at the backend.

Upvotes: 0

Rohit416
Rohit416

Reputation: 3486

It will not submit/pick the value from a disabled element. What you can do here is add a strongly type hidden field which will hold the value of the property. The model binder will do the rest i.e.

@Html.HiddenFor(m => m.isUsed)
// instead of..
@Html.CheckBoxFor(m => m.isUsed, new { @disabled="disabled"})

This way the Model.isUsed will have its value while submitting the form.

Upvotes: 5

user5061075
user5061075

Reputation:

You have to remove 'disabled' property before submitting the form. Suppose your form id is 'TestForm' then,

$('#TestForm').submit(function() {
        $('#CheckBoxId').removeAttr('disabled');
    });

Upvotes: 1

Related Questions