Mizbella
Mizbella

Reputation: 946

Checkbox Using Razor syntax in mvc4

I want to display a checkbox in view using razor syntax. the model property IsActive should be int. Model is:-

public class Student
    {
        public int StudentID { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public int IsActive { get; set; }           
}

View is:-

<div class="editor-label">
        @Html.LabelFor(model => model.IsActive)
    </div>
    <div class="editor-field">
        @Html.CheckBoxFor(model => model.IsActive)
        @Html.ValidationMessageFor(model => model.IsActive)
    </div>

I should display checkbox and if checkbox is checked,1 should be saved to the database and if umchecked 0 should be saved.

Pls help me... Thanks..

Upvotes: 0

Views: 9811

Answers (2)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

What don't you understand in the error message ? You can't use CheckBoxFor for an int property.

You should change your model and set

public bool IsActive {get;set;}

Now, there's probably a good reason for it to be an int, but hard to say why with your code...

if IsActive can be only 0 or 1, you should use a ViewModel class, and use a boolean property, which you will map to your class.

public class StudentViewModel
    {
        public int StudentID { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }           
}

then when you get your student from your db (in your "GET" action")

something like that (rustic)

public ActionResult StudentEdit(int id) {
  var student = getStudentById(id);
  var model = new StudentViewModel {
                  StudentId = student.StudentID,
                  Code = student.Code,
                  Description = student.Description,
                  IsActive = student.IsActive == 1 
              };

  return View(model);
}

Your view should be typed with StudentViewModel

@model StudentViewModel

then in your POST action, reverse

[HttpPost]
public ActionResult StudentEdit(StudentViewModel model) {
    var student = getStudentById(model.StudentID);
    student.Code = model.Code;
    student.Description = model.Description;
    student.IsActive = model.IsActive ? 1 : 0;
    UpdateStudent(student);

    return Redirect...
}

EDIT :

This is a really rustic answer, and I'm sure you could do better.

For that, we would need some more infos :

Are you using Entity Framework (version) ?

If yes, Code first, Database first, model first ?

Which database is behind ?

Can you change something to the database ?

What type has IsActive in database ?

Upvotes: 3

Cris
Cris

Reputation: 13351

IsActive should be a bool, @Html.CheckBoxFor() helper method expects boolean parameter

change code to

public bool IsActive { get; set; } 

Upvotes: 0

Related Questions