Pass values of checkBox to controller action in asp.net mvc4

后端 未结 12 1452
长发绾君心
长发绾君心 2020-12-14 00:31

I want to test if the checkbox is checked or not from my action method, what i need is to pass checkbox value from view to controller.

This is my view:



        
12条回答
  •  囚心锁ツ
    2020-12-14 01:22

    I hope this somewhat helps.

    Create a viewmodel for your view. This will represent the true or false (checked or unchecked) values of your checkboxes.

    public class UsersViewModel
    {
        public bool IsAdmin { get; set; }
        public bool ManageFiles { get; set; }
        public bool ManageNews { get; set; }
    }
    

    Next, create your controller and have it pass the view model to your view.

    public IActionResult Users()
    {
         var viewModel = new UsersViewModel();
         return View(viewModel);
    }
    

    Lastly, create your view and reference your view model. Use @Html.CheckBoxFor(x => x) to display checkboxes and hold their values.

    @model Website.Models.UsersViewModel
    
    @Html.CheckBoxFor(x => x.IsAdmin)

    When you post/save data from your view, the view model will contain the values of the checkboxes. Be sure to include the viewmodel as a parameter in the method/controller that is called to save your data.

    I hope this makes sense and helps. This is my first answer, so apologies if lacking.

提交回复
热议问题