Coffee shop is created with ASP.NET Core Razor page. Coffee Model created and all available coffee is stored in a db (ef core).
We have two pages. First page shows a table of all coffee (id, title, cost, …)info. Each coffee has an Edit "button".
<tbody>
@foreach (var item in Model._coffeeItems)
{....
<td>
@item.Price €
</td>
<td>
<a asp-action= "GetCoffeeItem" >Edit</a>
<a asp-action="RemoveCoffeeItem" >Delete</a>
</td> ...
When clicked should be redirected to an Edit page with a form. All fields must be filled with coffee information for easier edit.
In First page CoffeeItemProvider.cs:
public async Task<FoodItem> GetCoffeeItem(int id)
{
var item = await _db.CoffeeItems
.FirstOrDefaultAsync(i => i.Id == id);
return item;
}
public async Task UpdateCoffeeItem(int id, CoffeeItem item)
{
_db.CoffeeItems.Update(item);
await _db.SaveChangesAsync();
}
And in the Edit page:
<form asp-action="UpdateCoffeeItem">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" value = ""/>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
How can I fill in the input f.ex. Name with value = "@item.Name"?
Is there any way to make GetCoffeeItem to take in id from First page item when clicked – call GetCoffeeItem- get item – and then redirect to /Edit page with item and assign value = "@item.Smth"?
2
Answers
I ended up creating an EditModel for /Edit page. redoing a bit @balinta answer.
And in the Edit.cshtml.cs :
Just added @page "{id:int?}" on the top. and implemented
How about:
and in GetCoffeeItem return the Edit view instead, e.g.: