mardi 29 janvier 2019

How do I set the value of multiple checkboxes that is linked to an associated table because of many-to-many relationship MVC

I have a checkbox where the user can choose a number of services that can be provided to a company. I can save the services and that all works fine. The services are linked to a company through a CompanyService table which as the companyId and the serviceId.

If the user clicks on an edit button I am unsure how to have the boxes checked on load. I've had a look at other options using IsChecked however I cannot add a property to my services model as it serves multiple companies. How would I go about doing it?

My Service Model

    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    public virtual ICollection<CompanyService> CompanyServices { get; set; }
    public virtual ICollection<TrustService> TrustServices { get; set; }

My CompanyService model

    [Key]
    [Column(Order =1)]
    public int CompanyId { get; set; }
    [Key]
    [Column(Order =2)]
    public int ServiceId { get; set; }

    public virtual Company Company { get; set; }
    public virtual Service Service { get; set; }

And finally the Razor code

<div class="col-lg-5">
                <div class="col-12">
                    <ul class="list-group" id="serviceList">
                        <li class="list-group-item service-heading">Services</li>
                        @foreach (var service in Model.Services)
                        {
                            <li class="list-group-item">
                                <input type="checkbox" name="services" value="@service.Id" id="check_@service.Id" />
                                <label for="check_@service.Id">@service.Name</label>
                            </li>
                        }
                    </ul>
                </div>
            </div>

Do I need to create a IsChecked on my CompanyServices table and try and assign the checked value from there? If so how would I do that?




Aucun commentaire:

Enregistrer un commentaire