Search code examples
c#asp.net-mvccheckboxtextbox

Capture Textbox value through a CheckBox asp.net MVC


There is a Form which consists of Textbox which are activated or deactivated by a CheckBox ....

How can I capture the value that the user enters validating that the Check is marked?

View

My View:

  <script type="text/javascript">
        $(function (){
            $("#idcheckproveedor").change(function(){
                var st = this.checked;
                if (st) {
                    $("#txtSearch").prop("disabled", false);
                }
                else {
                    $("#txtSearch").prop("disabled", true);
                }
                });
            });
    </script>

  <div class="form-group">
  <label>Proveedor</label>
  <input type="checkbox" id="idcheckproveedor" checked="checked" />
  @Html.TextBox("searchTerm", null, new { @class = "form-control", id = "txtSearch" })
 </div>

Solution

  • You can give a name to your checkbox element as the values would be posted as key value pair using the name attribute as key, so you can do following in view:

    <input type="checkbox" name="AllowSearch" id="idcheckproveedor" checked="checked" />
    @Html.TextBox("searchTerm", null, new { @class = "form-control", id = "txtSearch" })
    

    and in action you will have for checkbox a parameter with name AllowSearch which will be of type bool to hold the either the checkbox was checked or not when posted:

    [HttpPost]
    public ActionResult BuscarRecepcion(string searchTerm, bool AllowSearch_
    { 
    
        // validate here 
    
        if(AllwoSearch)
        {
           // do search
        }
    
        // else send back to view as validation failed.
    
    }