Answer the question
In order to leave comments, you need to log in
What to do if the data is not saved when clicking on Add in this layout?
The data that is filled in this form should be added to this view
public class HomeController : Controller
{
private IRepository repository;
public HomeController(IRepository repo) => repository = repo;
public IActionResult Index() => View(repository.Products);
[HttpPost]
public IActionResult AddProducts(Product product)
{
repository.AddProduct(product);
return RedirectToAction(nameof(Index));
}
}
public class DataRepository : IRepository
{
private List<Product> data = new List<Product>();
public IEnumerable<Product> Products => data;
public void AddProduct(Product product)
{
this.data.Add(product);
}
}
public interface IRepository
{
public IEnumerable<Product> Products { get; }
void AddProduct(Product product);
}
public class Product
{
public string Name { get; set; }
public string Category { get; set; }
public decimal PurchasePrice { get; set; }
public decimal RetailPrice { get; set; }
}
@model IEnumerable<Product>
<h3 class="p-2 bg-primary text-white text-center">Products</h3>
<div class="container-fluid mt-3">
<div class="row">
<div class="col font-weight-bold">Name</div>
<div class="col font-weight-bold">Category</div>
<div class="col font-weight-bold">Purchase Price</div>
<div class="col font-weight-bold">Retail Price</div>
<div class="col"></div>
</div>
<form asp-action="AddProduct" method="post">
<div class="row">
<div class="col"><input name="Name" class="form-control" /></div>
<div class="col"><input name="Category" class="form-control" /></div>
<div class="col">
<input name="PurchasePrice" class="form-control" />
</div>
<div class="col">
<input name="RetailPrice" class="form-control" />
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
@if (Model.Count() == 0)
{
<div class="row">
<div class="col text-center p-2">No Data</div>
</div>
}
else
{
@foreach (Product p in Model)
{
<div class="row p-2">
<div class="col">@p.Name</div>
<div class="col">@p.Category</div>
<div class="col text-right">@p.PurchasePrice</div>
<div class="col text-right">@p.RetailPrice</div>
<div class="col"></div>
</div>
}
}
</div>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question