0

I`m using these checkboxes in my view:

<input type="checkbox" value="1" name="reglist" id="prueba2" />
<input type="checkbox" value="2" name="reglist" id="prueba3" />

I`m using entity framework and My viewModel table does not contain values for those checkbox.

I need to get the checkbox checked in the controller and keep the ones that were checked previously along requests without binding the chexboxes to classes.

2 Answers 2

1

Just so that we're speaking the same language, I typically refer to the things that I save in the database as the "model" and what I use as the model on the view as the "view model".

In that, I would have a model as such:

public class Person{
   // properties
}

And then I would have a view model like so:

public class PersonViewModel{
   public Person Person { get; set; }
   public bool OtherNeededValue1 {get; set;}
   public bool OtherNeededValue2 {get; set;}
}

Now, on your view, user PersonViewModel as the model. Then, in your controller, your action will look like this:

public ActionResult Create (PersonViewModel viewModel)
{
     if (viewModel.OtherNeededValue1)
     {
         // do something
     }

     var p = new Person { 
                          FirstName = viewModel.Person.FirstName 
                        };

}

This way you don't cloud your model with unnecessary properties, but you can still take advantage of the rich binding of MVC.

Cheers.

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

Comments

0

You can make an AJAX call to your controller every time a checkbox is clicked.

Ajax Call

    $(function () {
        $(':checkbox').change(function () {
            $.ajax({
                url: '@Url.Action("CheckBoxStatus")',
                type: 'POST',
                data: { isChecked: $(this).is(':checked'),
                        id: $(this).val()
                },
                success: function (result) { }
            });
        });
    });

this will send the status and the value of the checkbox to the controller and the you can store the info in whatever way like.

Controller Method

public void CheckBoxStatus(bool isChecked, int id)
{
   // Do what you like here 
}

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.