I have a checkbox list where the values are loaded from a database table. When the user selects particular customer, it is updating the database value to '1', but in the razor pages view the values are showing unchecked. I am not sure where i am going wrong.
Please find my code below,
AccessRights.Cs(Model Class)
public class AccessRights
{
[Key]
public int Id { get; set; }
public int EmployeeId { get; set; }
[Display(Name = "Users")]
public string Username { get; set; }
public string ADUsername { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public bool isSelected { get; set; }
public string CreatedBy { get; set; }
public DateTime? CreatedTimeStamp { get; set; }
public string LastModifiedBy { get; set; }
public DateTime? LastModifiedTimeStamp { get; set; }
}
Edit.Cshtml
<div class="form-group">
<label class="control-label"> Access To Customers</label>
<div class="checkbox checkboxlist">
@{
foreach (var customers in Model.CustomersChecked)
{
<input type="checkbox" id="@customers.Value" value="@customers.Value" name="CustomersChecked" checked="@customers.Selected" />
<label class="text-black">@customers.Text</label><br/>
//<input type="hidden" asp-for="@Model.CustomersChecked" value="@customers.Id">
}
}
</div>
<span class="text-danger"></span>
</div>
Edit.Cshtml.Cs
[BindProperty]
public List<SelectListItem> CustomersChecked { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null || _context.AccessRights == null)
{
return NotFound();
}
var accessrights = await _context.AccessRights.FirstOrDefaultAsync(m => m.EmployeeId == id);
AccessRights = accessrights;
CustomersChecked = (from p in _context.AccessRights.Where(m => m.EmployeeId == id)
select new SelectListItem
{
Text = p.CustomerName,
Value = p.CustomerId.ToString()
}).ToList();
//CustomersChecked = CustomersChecked.Where()
return Page();
}
public async Task<IActionResult> OnPostAsync(string[] CustomersChecked)
{
List<SelectListItem> items = (from p in _context.AccessRights.Where(m => m.EmployeeId == AccessRights.EmployeeId)
select new SelectListItem
{
Text = p.CustomerName,
Value = p.CustomerId.ToString()
}).ToList();
foreach (SelectListItem item in items)
{
if (CustomersChecked.Contains(item.Value))
{
item.Selected = true;
}
else
{
item.Selected = false;
}
AccessRights.LastModifiedBy = HttpContext.Session.GetString("DisplayName").Trim();
AccessRights.LastModifiedTimeStamp = DateTime.Now;
await _context.Database.ExecuteSqlInterpolatedAsync($"UPDATE [AccessRights] SET [isSelected] = {item.Selected}, [LastModifiedBy] = {AccessRights.LastModifiedBy}, [LastModifiedTimeStamp] = {AccessRights.LastModifiedTimeStamp} WHERE [EmployeeId] = {AccessRights.EmployeeId} AND [CustomerName] = {item.Text}");
}
return RedirectToPage("./Index");
}
Appreciate your help! Thanks!
Aucun commentaire:
Enregistrer un commentaire