1 | initial version |
Here are the steps for creating a Checkbox List using Entity Framework in ASP.Net Core web API:
public class Color
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsChecked { get; set; }
}
public class CheckboxListContext : DbContext
{
public CheckboxListContext(DbContextOptions<CheckboxListContext> options) : base(options)
{}
public DbSet<Color> Colors { get; set; }
}
services.AddDbContext<CheckboxListContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
[ApiController]
[Route("api/[controller]")]
public class ColorsController : ControllerBase
{
private readonly CheckboxListContext _context;
public ColorsController(CheckboxListContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Color>>> GetColors()
{
return await _context.Colors.ToListAsync();
}
[HttpPut]
public async Task<IActionResult> UpdateColors(IEnumerable<Color> colors)
{
foreach (var color in colors)
{
_context.Entry(color).State = EntityState.Modified;
}
await _context.SaveChangesAsync();
return NoContent();
}
}
@model IEnumerable<Color>
<form method="post" action="/api/colors">
@foreach (var color in Model)
{
<div>
<input type="checkbox" name="colors[@color.Id].IsChecked" @if (color.IsChecked) { <text>checked</text> } />
<label>@color.Name</label>
</div>
}
<button type="submit">Update</button>
</form>
public static void Initialize(CheckboxListContext context)
{
if (!context.Colors.Any())
{
context.Colors.AddRange(
new Color { Name = "Red" },
new Color { Name = "Green" },
new Color { Name = "Blue" }
);
context.SaveChanges();
}
}