2

I want to bind a checkbox to an integer (the ISACTIVE value shown below) in ASP.net MVC.

@Html.CheckBoxFor(model => model.ISACTIVE, new { htmlAttributes = new { @class = "form-control" } })

I know that Html.CheckBoxFor only accepts bool as input and I could add a new property on my Model, but I'm using an already existing database and every time it updates, the Model gets refreshed.

Is there a way to create a new method for CheckBoxFor that would return an integer based on if the box is checked or not?

11
  • Use a view model with a boolean property (and you can only use CheckBoxFor() for boolean properties) Commented Apr 20, 2015 at 9:12
  • While sending the model why dont u return bool only ...I mean for postive numbers except 0 send True and for 0 send False. Commented Apr 20, 2015 at 9:16
  • @StephenMuecke I can't do that since my model reverts back to it's original state every time the database updates. I was looking for a way to change the original CheckBoxFor method or add a new similar one that changes the bool input to an integer. Commented Apr 20, 2015 at 9:18
  • @TusharGupta I assume you're suggesting I add a new helper method that changes the int to bool? That would be nice, but how could I make the above line of code to work like that? Commented Apr 20, 2015 at 9:20
  • A view model is NOT a data model. What is a view model in MVC. Every view should have a view model! Commented Apr 20, 2015 at 9:21

4 Answers 4

1

You could also try using simple HTML input control for checkbox type. That way, you can assign some value or name to it and return it to the controller as well.

This might not be the exact thing that you are trying to achieve. It would give you an idea though.

In your view :

<input type="checkbox" id="yourId" name="selectedIds" value="@menu.Id"/>

In your controller, you can try accessing this particular control's value like this :

value = Request.Form["selectedIds"];

Hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems like a clean solution but I keep getting "The value 'true' is not valid for Active" error when I try to submit the form with the box checked. When it's unchecked it works fine. I searched around for solutions to this but I keep getting variations of this error.
Nevermind, I figured it out and it works perfectly now. Thank you! On my view I added <input type="checkbox" name="myCheckbox" id="myCheckbox" value="1" /> And on my controller I got the values with if (myCheckbox[0] == "1") active= 1;
Great Work ! Glad to help. Thanks,
0

Option 1

Since you can't add a new property to your entity why don't you just check the bool value in your action?

public ActionResult Test(bool isActive)
{

    int test = isActive ? 1 : 0;


    return View();
}   

Option 2

Create your own view model which checks the boolean value and then creates a new entity record.

Model

public class NikolsModel
{

    [Required]
    public bool IsActive { get; set; }

    // Other Properties...

}

Action

    public async Task<ActionResult> Index(NikolsModel model)
    {

        if (ModelState.IsValid)
        {
            //
            // Create a new instance of your entity 
            //
            var record = new NikolsEntity
            {
                IsValid = model.IsActive ? 1 : 0,
                //Other properties from model
            };

            DbContext.NikolsEntity.add(record);

            await DbContext.SaveChangesAsync();

            return RedirectToAction("Index");
        }


        //Something went wrong, return the view with model errors
        return View(model);

    }

3 Comments

That would make sense but model => model.ISACTIVE would still return an error since ISACTIVE is an int.
Can you do it in script? How are you creating the request, with a form or with Ajax?
With a form in my view. Like <div class="form-group"> @Html.LabelFor(model => model.ISACTIVE, htmlAttributes: new { @class = "control-label " }) <div> @Html.CheckBoxFor(model => model.ISACTIVE, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ISACTIVE, "", new { @class = "text-danger" }) </div> </div>
0

Add bool property to your model:

public bool BoolValue
{
    get { return IntValue == 1; }
    set { IntValue = value ? 1 : 0;}
}

public int IntValue { get; set; }

EDIT:

You can also create checkbox control manually:

@Html.CheckBox("IsActive", Model.IsActive ?  true : false,  new { htmlAttributes = new { @class = "form-control" } }) 

If name will match the name generated previously by MVC, this value should come back to controller action. Maybe you must define own custom value provider to convert from bool to int similarly to: How to map a 1 or 0 in an ASP.Net MVC route segment into a Boolean action method input parameter

1 Comment

I already explained why that's not possible in my question. My model gets reverted back to the original every time the database updates and thus I can't add more properties.
0
@Html.CheckBoxFor(model => model.Modelname)

and then, in your Controller:

var isChecked = Request.Form["Modelname"];

if(!isChecked.Equals("false"))
{
//Checkbox is checked, do whatever you want!

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.