Razor Page渲染页两次.net5
CARS
Razor Page是在第一次加载时两次调用 onget()
。当我单击“查看”按钮<代码>视图剃须刀页面 Onget(int ID)
两次。
service.submit
方法正在插入两个记录,而不是一个记录。
它不应该只调用每个页面方法一次吗?
cars.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>
}
cars.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;
}
}
}
view.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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请允许我在这里写一个样本。我在CSHTML中有一个表格,并提供
Onpost
方法来处理它,然后使用依赖注入来注入服务来处理数据库插入方法。Please allow me write a sample here. I had a form in cshtml and provide
OnPost
method to handle it, then using Dependency Injection to inject service to handle the database inserting method.