How do I bind checkboxes to the List property of a view model?

后端 未结 4 1439
暗喜
暗喜 2020-12-11 18:35

I\'ve been reading the various posts on view models and check boxes, but my brain is starting to lock up and I need a little push in the right direction.

Here\'s my

4条回答
  •  無奈伤痛
    2020-12-11 19:17

    Have your View Model like this to represent the CheckBox item

    public class ChannelViewModel 
    {
      public string Name { set;get;}
      public int Id { set;get;}
      public bool IsSelected { set;get;}
    }
    

    Now your main ViewModel will be like this

    public class AlertViewModel
    {
      public int AlertId { get; set; }
      public List UserChannelIds { get; set; }      
      //Other Properties also her
    
      public AlertViewModel()
      {
        UserChannelIds=new List();       
      }
    
    }
    

    Now in your GET Action, you will fill the values of the ViewModel and sent it to the view.

    public ActionResult AddAlert()
    {
        var vm = new ChannelViewModel();
    
        //The below code is hardcoded for demo. you mat replace with DB data.
        vm.UserChannelIds.Add(new ChannelViewModel{ Name = "Test1" , Id=1});
        vm.UserChannelIds.Add(new ChannelViewModel{ Name = "Test2", Id=2 });
    
        return View(vm);
    }
    

    Now Let's create an EditorTemplate. Go to Views/YourControllerName and Crete a Folder called "EditorTemplates" and Create a new View there with the same name as of the Property Name(ChannelViewModel.cshtml)

    Add this code ro your new editor template.

    @model ChannelViewModel
    

    @Model.Name : @Html.CheckBoxFor(x => x.IsSelected)
    @Html.HiddenFor(x=>x.Id)

    Now in your Main View, Call your Editor template using the EditorFor Html Helper method.

    @model AlertViewModel
    

    AddTag

    @using (Html.BeginForm()) {
    @Html.LabelFor(m => m.AlertId) @Html.TextBoxFor(m => m.AlertId)
    @Html.EditorFor(m=>m.UserChannelIds)
    }

    Now when You Post the Form, Your Model will have the UserChannelIds Collection where the Selected Checkboxes will be having a True value for the IsSelected Property.

    [HttpPost]
    public ActionResult AddAlert(AlertViewModel model)
    {
       if(ModelState.IsValid)
       {
          //Check for model.UserChannelIds collection and Each items
          //  IsSelected property value.
          //Save and Redirect(PRG pattern)
       }
       return View(model);
    }
    

提交回复
热议问题