Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My user model has an int property called active (its an int because I didn't create the model nor the database, its getting used as a boolean..). I'm creating the action /Users/Edit/ that will be editting the model, so I've got a form with a checkbox for the active property. When the submit button is pressed the model binder will put all the form data together into one single object and pass it as a parameter to /Users/Edit.

But when I try to save the changes to the database, I check ModelState.isValid and it returns false because the model binder won't change the boolean into an integer.

How can I solve this problem?

share|improve this question
    
A checkbox represents true or false. Why don't you just use a bool and call it a day? –  Ek0nomik May 31 '13 at 21:03
    
because I didnt create the database and in the database its an int –  user1534664 May 31 '13 at 21:04
1  
Are you able to edit the Db? It should be a bit –  James May 31 '13 at 21:04
    
Are you using the exact same object type for your view and database? Ideally you could change your view model and then if you need to fix up the data before going into the database then you can do that when the database model is populated. –  Ek0nomik May 31 '13 at 21:05
1  
No Problem. Have fun :) - i will stick it in a solution so you can close this once you implement it –  James May 31 '13 at 21:10
show 3 more comments

2 Answers

up vote 1 down vote accepted

1) Edit Db to make it a bit

2) Change the property on your view model to a bool

3) Use DisplayFor in your Razor View

It will now automatically generate a checkbox and check it accordingly.

share|improve this answer
add comment

Let's assume worst case that you cannot change your Db to a bool. Then you would use a View Model to perform the data transformation for you.

Say your user model is such:

public class StaticModel {

    public string description { get; set; }
    public int IsActive { get; set; }

}

Then you create a view model (facade style):

public class StaticModelFacade {

    StaticModel _value;    

    public StaticModelFacade(StaticModel value) {

        _value = value;

    }

    public string description {
        get {return _value.description;}
        set {_value.description = value;}
    }

    public bool IsActive {
        get { return _value.IsActive = 1; }
        set { _value.IsActive = value ? 1 : 0 }
    }

}

Your view now binds to a bool and all is wired up Ok.

share|improve this answer
    
Thanks. James method works for me better since I can just change it to a bool but this is nice to know =) –  user1534664 May 31 '13 at 21:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.