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?

NikolMarg
  • 43
  • 2
  • 9
  • Use a view model with a boolean property (and you can only use `CheckBoxFor()` for boolean properties) –  Apr 20 '15 at 09: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. – Tushar Gupta Apr 20 '15 at 09: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. – NikolMarg Apr 20 '15 at 09: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? – NikolMarg Apr 20 '15 at 09:20
  • A view model is NOT a data model. [What is a view model in MVC](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc). Every view should have a view model! –  Apr 20 '15 at 09:21
  • Nope @NikolMarg i'm saying that for example `ISACTIVE` is a positive integer then add a property Boolean property and assign it True and bind hat new property withe the checkbox – Tushar Gupta Apr 20 '15 at 09:24
  • @StephenMuecke So far I don't have a view model for all my views since the views use the model created from the entity framework directly. I guess I could create a view model for this specific view but that's not really what I'm trying to do. – NikolMarg Apr 20 '15 at 09:26
  • @NikolMarg, _but that's not really what I'm trying to do_? So are you saying you want your web site to fail! –  Apr 20 '15 at 09:44
  • @StephenMuecke Wow that escalated quickly – heymega Apr 20 '15 at 09:49
  • @NikolMarg Can you give us some more code, please? We really need to see your entity & actions if that's OK :) – heymega Apr 20 '15 at 09:49
  • @StephenMuecke At least according to what I read, when working database-first you don't need to have a view model for every single view. I guess that creating a view model would be an easy workaround, though it's unneeded in most of my views and they work fine as is. – NikolMarg Apr 20 '15 at 09:55

4 Answers4

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.

Dhrumil
  • 3,221
  • 6
  • 21
  • 34
  • 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. – NikolMarg Apr 20 '15 at 10:13
  • Nevermind, I figured it out and it works perfectly now. Thank you! On my view I added `` And on my controller I got the values with `if (myCheckbox[0] == "1") active= 1;` – NikolMarg Apr 20 '15 at 10:37
  • Great Work ! Glad to help. Thanks, – Dhrumil Apr 20 '15 at 10:40
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

Community
  • 1
  • 1
suvroc
  • 3,058
  • 1
  • 15
  • 29
  • 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. – NikolMarg Apr 20 '15 at 09:16
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);

    }
heymega
  • 9,215
  • 8
  • 42
  • 61
  • That would make sense but `model => model.ISACTIVE` would still return an error since ISACTIVE is an int. – NikolMarg Apr 20 '15 at 09:30
  • Can you do it in script? How are you creating the request, with a form or with Ajax? – heymega Apr 20 '15 at 09:30
  • With a form in my view. Like `
    @Html.LabelFor(model => model.ISACTIVE, htmlAttributes: new { @class = "control-label " })
    @Html.CheckBoxFor(model => model.ISACTIVE, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ISACTIVE, "", new { @class = "text-danger" })
    `
    – NikolMarg Apr 20 '15 at 09:32
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!

}
Umit Kaya
  • 5,771
  • 3
  • 38
  • 52