我对 C# razorpages 比较陌生。我使用实体框架创建了一个示例项目,并使用 ScaffoldedItems 功能生成了我的页面。
我想要一个模式弹出窗口来从索引页面创建记录,而不是创建页面,但我正在努力让它们工作。
我的模式弹出窗口带有一个文本框,但是当单击提交时,我立即从显示表格的循环中收到 NullReferenceException。
请帮忙。
@page
@model ResellingWEB.Pages.Brands.IndexModel
@{
ViewData["Title"] = "Brands";
}
<h1>Brands</h1>
<p>
<a asp-page="Create">Create New</a>
</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="post" asp-page="./Index" asp-handler="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label class="control-label">Brand Name</label>
<input class="form-control" required="required" name="BrandName" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
</div>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Brand[0].BrandName)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Brand) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.BrandName)
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.BrandID">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.BrandID">Details</a> |
<a asp-page="./Delete" asp-route-id="@item.BrandID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using ResellingWEB.Data;
using ResellingWEB.Models;
namespace ResellingWEB.Pages.Brands
{
public class IndexModel : PageModel
{
private readonly ResellingWEBContext _context;
public ResellingWEBContext Context => _context;
public IndexModel(ResellingWEBContext context)
{
_context = context;
}
public IList<Brand> Brand { get;set; } = default!;
public async Task OnGetAsync()
{
Brand = await _context.Brands.ToListAsync();
}
public async Task<IActionResult> OnPostCreateAsync(string BrandName)
{
if (!ModelState.IsValid)
{
return Page();
}
var brand = new Brand { BrandName = BrandName };
_context.Brands.Add(brand);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}