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"?
CodePudding user response:
How about:
...
<td>
<a asp-action="GetCoffeeItem" asp-route-id="@item.Id">Edit</a>
<a asp-action="RemoveCoffeeItem" asp-route-id="@item.Id">Delete</a>
</td>
...
and in GetCoffeeItem return the Edit view instead, e.g.:
return View("Edit", coffeeModel);
CodePudding user response:
I ended up creating an EditModel for /Edit page. redoing a bit @balinta answer.
<a asp-page="./Edit" asp-route-id="@item.Id">Edit</a>
<button class="btn btn-primary" type="submit" asp-page-handler="delete"
asp-route-id="@item.Id">Delete
</button>
And in the Edit.cshtml.cs :
Just added @page "{id:int?}" on the top. and implemented
public async Task<IActionResult> OnGetAsync(int id) function.