Carsrazor 頁面在第一次加載時呼叫OnGet()了兩次。當我單擊查看按鈕View剃刀頁面加載OnGet(int id)兩次。
Service.Submit方法是插入兩條記錄而不是一條。它不應該只呼叫每個頁面方法一次嗎?
汽車.cshtml
@page
@model IndexModel
@using MyApp.Models;
@{
<table class="table">
<thead>
<tr>
<th>Reference No</th>
<th>Car Make</th>
<th>Car Model</th>
<th>Price</th>
<th>Year</th>
</tr>
</thead>
<tbody>
@foreach (Car item in Model.CarList)
{
<tr>
<td>@item.ReferenceNo</td>
<td>@item.Make</td>
<td>@item.Model</td>
<td>@item.Price</td>
<td>@item.Year</td>
<td>
<a asp-page="View" asp-route-id="@item.id" class="btn btn-success btn-sm text-white">View</a>
</td>
</tr>
}
</tbody>
</table>
}
汽車.cshtml.cs
public class IndexModel : PageModel
{
private readonly AppDbContext _context;
public List<Car> CarList = new List<Car>();
public IndexModel(AppDbContext context)
{
_context = context;
}
public void OnGet() // -----> this function is invoked twice.
{
try
{
CarList = _context.Car.FromSqlRaw("EXEC dbo.sp_GetCars").ToList();
}
catch (Exception)
{
throw;
}
}
}
視圖.cshtml.cs
public class ViewModel : PageModel
{
private readonly AppDbContext _context;
private readonly IServiceScopeFactory _scopeFactory;
public ViewModel(AppDbContext context, IServiceScopeFactory scopeFactory)
{
_context = context;
_scopeFactory = scopeFactory;
}
public IActionResult OnGet(int id)
{
try
{
if (id != null) {
Service.Submit(id, _scopeFactory); ------>Insert function is also invoked twice
}
return RedirectToPage("Index");
}
catch (Exception)
{
throw;
}
}
}
uj5u.com熱心網友回復:
請允許我在這里寫一個示例。我在cshtml中有一個表單并提供OnPost了處理它的方法,然后使用依賴注入注入服務來處理資料庫插入方法。
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<form method="post">
<table>
<tr>
<td>ID: </td>
<td><input type="text" id="ID" name="ID"/></td>
</tr>
<tr>
<td>Title: </td>
<td><input type="text" id="Title" name="Title"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit buttom" /></td>
</tr>
</table>
<hr/>
</form>
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly ICommonService _commonService;
public IList<Movie> Movie { get; set; }
public IndexModel(ILogger<IndexModel> logger, ICommonService commonService)
{
_logger = logger;
_commonService = commonService;
}
public void OnGet()
{
Movie = _commonService.getData();
}
public void OnPost(Movie mov) {
var a = mov.Title;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490419.html
標籤:C# asp.net-mvc asp.net 核心 剃刀页面 asp.net-core-5.0
