C
C#17mo ago
cnetworks

❔ Need help in dynamically binding checkbox values in Edit View

I am doing a cru in .net core mvc. i have a country field which checkboxes. while dynamically fetching values from db and to send values to edit view, it stack selected items into one group and unselected item into one my output attached below in end (my output pic attached) my view code is: @foreach (var country in ViewBag.Countries) { <div> <input type="checkbox" id="@country.Value" name="Country" value="@country.Value" @(Model.Country!=null&& Model.Country.Contains(country.Value) ? "checked" : "") /> <label for="@country.Value">@country.Text</label> @<label class="form-check-label">@country</label>@ </div> My Action code here [HttpGet] Action Edit var allCcountries = _context.RegistTables .Select(r => r.Country) .Distinct() .OrderBy(c => c) .ToList(); var selectedCountries = registration?.Country?.Split(","); ViewBag.Countries = allCcountries.Select(c => new SelectListItem { Value = c, Text = c, Selected = selectedCountries != null && selectedCountries.Contains(c) }); return View(registration);
1 Reply
Accord
Accord17mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.