You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Razor Pages发票创建关联客户表的问题咨询

ASP.NET Core Razor Pages 发票表单关联客户问题解决

1. 在AddInvoice页面模型中添加对Customer表的引用

通过依赖注入DbContext直接访问Customer表,具体操作如下:

  • 在页面模型构造函数中注入应用的DbContext;
  • 定义List<Customer>类型属性存储客户列表;
  • 在OnGetAsync方法中查询所有客户并赋值,表单提交验证失败时,也要重新加载客户列表避免页面下拉框为空。

示例代码:

public class AddInvoiceModel : PageModel
{
    private readonly AppDbContext _dbContext;

    public AddInvoiceModel(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    [BindProperty]
    public Invoice Invoice { get; set; }
    public List<Customer> Customers { get; set; }

    public async Task OnGetAsync()
    {
        Customers = await _dbContext.Customers.ToListAsync();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            Customers = await _dbContext.Customers.ToListAsync();
            return Page();
        }

        _dbContext.Invoices.Add(Invoice);
        await _dbContext.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

2. 显示客户名称而非ID(用下拉框选择)

在Razor页面表单中使用下拉框展示客户名称,提交时自动传递对应CustomerId,同时通过数据验证避免空值引发SQL异常:

第一步:给Invoice实体添加验证

在CustomerId属性上标记[Required],强制用户选择客户:

public class Invoice
{
    public int Id { get; set; }
    // 其他发票属性...

    [Required(ErrorMessage = "请选择客户")]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }
}

第二步:在Razor页面添加下拉框

<div class="form-group">
    <label asp-for="Invoice.CustomerId" class="control-label">客户</label>
    <select asp-for="Invoice.CustomerId" 
            asp-items="@(new SelectList(Model.Customers, "Id", "Name"))" 
            class="form-control">
        <option value="">请选择客户</option>
    </select>
    <span asp-validation-for="Invoice.CustomerId" class="text-danger"></span>
</div>

注:假设Customer类包含Name属性用于显示客户名称,若你的属性名不同,替换成对应字段即可。

这样用户在页面看到的是客户名称,选择后提交的是对应的CustomerId,无需手动输入,同时验证规则避免了空值导致的SQL异常。

内容的提问来源于stack exchange,提问作者D M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:37:18