Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created Feb 9, 2022
Embed
What would you like to do?
using System.Threading.Tasks;
using Catalog;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Demo.Controllers
{
public class ProductCrudController : Controller
{
private readonly CatalogDbContext _catalogDbContext;
public ProductCrudController(CatalogDbContext catalogDbContext)
{
_catalogDbContext = catalogDbContext;
_catalogDbContext.Database.EnsureCreated();
}
[HttpGet("/productCrud/{sku}")]
public async Task<IActionResult> GetProduct(string sku)
{
var record = await _catalogDbContext.Products
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Sku == sku);
if (record == null)
{
return NotFound();
}
return View(record);
}
[HttpPost("/productCrud/{sku}")]
public async Task<IActionResult> UpdateProduct([FromRoute] string sku, [FromForm]CatalogProduct product)
{
var record = await _catalogDbContext.Products.SingleOrDefaultAsync(x => x.Sku == sku);
if (product == null)
{
return NotFound();
}
record.Description = product.Description;
record.Name = product.Name;
record.Price = product.Price;
record.Cost = product.Cost;
record.QuantityOnHand = product.QuantityOnHand;
record.ForSale = product.Price;
record.FreeShipping = product.FreeShipping;
await _catalogDbContext.SaveChangesAsync();
return RedirectToAction("GetProduct", new { sku = sku });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment