Help with MVC Pick up checkbox value and send to bool variable controller

Asked

Viewed 442 times

-1

I’m trying to send the value of checkboxwith id, if the checkbox be it true, will create the column.

VIEW

<div class="checkbox dadospessoais">
                                            <label>
                                                <input class="dadospessoais" type="checkbox" name="ckNome" id="ckNome" /> Nome
                                            </label>
                                        </div>
                                        <div class="checkbox">
                                            <label>
                                                <input class="dadospessoais" type="checkbox" name="ckNomeSocial" id="ckNomeSocial" /> Nome Social
                                            </label>
                                        </div>

MODEL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;



namespace QJW.Web.Models.RHViewModel
{

 public class FiltroRelatorioCheckbox
    {


        public bool ckNome { get; set; }

        public bool ckNomeSocial { get; set; }

 }

CONTROLLER

PART OF WHERE I WANT TO WORK WITH THE RESULTS OF CHECKBOX.

public ActionResult Imprimir( QJW.Web.Models.RHViewModel.FiltroRelatorioCheckbox ckModel)

 {


             if (ckModel.ckNome)
            {
                new DataColumn("Nome", typeof(string)) { AllowDBNull = true };     
            }


}

I put a breakpoint in the if, and the ckNome always comes false.

  • You use routes or controller/action?

  • use but for other screen, I’m trying to get the value of the checkbox only use this actionResult there that I put

2 answers

1

How are you sending this form to the controller?

You have to assign the value true to the checkbox before sending it to the controller.

You can use a js function. Example:

$(document).on("click", "[type='checkbox']", function(e) {
        if (this.checked) {
            $(this).attr("value", "true");
        } else {
            $(this).attr("value","false");}
    });

1

Personal in case someone is with the same doubt, I solved in this way:

<div class="checkbox dadospessoais">
    <label>
        <input class="dadospessoais" type="checkbox" name="ckNome" id="ckNome" value="true" /> Nome
        <input name="ckNome" id="ckNome" value="false" type="hidden" />
    </label>
</div>

Adding a value="true" in the input and value="false" the other being hidden he will send false or true.

Browser other questions tagged

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