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();
}
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-07 14:52:45 +0000
Seen: 8 times
Last updated: May 07 '23
How can ADOMD.NET be used to deploy UDFs (User defined functions) to SSAS?
How can a database in SQL Server Managed Instance be backed up to the local file system?
How can a file be restored on Google Cloud for SQL Server 2019 without the use of buckets?
How does MySQL master-slave replication work on Windows?
How is incrementing done in SAS proc sql?
What is the SAS coding method to change Row 1 into a variable without using proc SQL?
How can a counter be added specifically for one record using SQL/SAS?
What is the process for installing SASS/Compass in the DDEV web container?