Home Creating and binding razor checkboxes from a list
Reply: 0

Creating and binding razor checkboxes from a list

user2363
1#
user2363 Published in May 21, 2018, 3:10 am

It's been a while since I wrote razor and I'm stuck at creating checkboxfor options from a list and make it work. I tried some other answers but none solved the case for me so far.

This is the model I'm using in the view. I'm trying to create checkboxes for Roles.

public class AccountRegisterModel
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string emailAddresses { get; set; }
        public string password { get; set; }
        public string passwordConfirm { get; set; }
        public bool? isactive { get; set; }
        public string phone { get; set; }
        public string subscriptionKey { get; set; }
        public string SalesPersonReference { get; set; }
        public int ProjectId { get; set; }
        public int SalesPersonId { get; set; }
        public int? SalesRegionId { get; set; }

        public List<SelectListModel> Roles { get; set; }

        public List<SelectListModel> Projects { get; set; }
        public List<SelectListModel> SalesRegions { get; set; }
        public int TenantID { get; set; }
        public Guid TenantGuid { get; set; }
        public string UserID { get; set; }
        public string UserEmail { get; set; }
    }

Type of Roles, SelectListModel

public class SelectListModel
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public bool Selected { get; set; }
        public string ProjectHierarchyCode { get; set; }
        public string SalesRegionReference { get; set; }
        public int? Depth { get; set; }
        public bool isSelected { get; set; }
    }

The way I tried to create the checkboxes

@foreach (var item in Model.Roles)
{
  @Html.CheckBoxFor(m=> item.isSelected, new { value = item.Value, id= "chkRole_"+item.Value})
}

Models "Roles" list gets populated in the controller and I get 9 unnamed checkboxes on the page. Naming them can be solved with a label so it's not a problem.

Problem is, when I check some of the boxes and hit "Save", chosen roles are not getting posted to the controller. Roles field in the model paramater comes null. So I think I have a binding issue.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323079 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO