ASP.NET Core Razor Pages模型绑定

gopyfrb3  于 2023-07-01  发布在  .NET
关注(0)|答案(3)|浏览(144)

我是ASP.NET核心剃刀页面的新手,我希望你能在以下方面提供帮助。
我有以下两个类:

public class Customer
{
    [Key]
    public int Id { get; set; }
    [Required(ErrorMessage ="Please enter a name.")]
    [Display(Name ="Customer Name")]
    public string CustomerName { get; set; }
    [Display(Name = "Customer Email")]
    public string CustomerEmail { get; set; } = string.Empty;
    [Display(Name ="Customer Phone Number")]
    public string CustomerPhoneNumber { get; set; } = string.Empty;

    public List<Invoice> Invoices { get; set; } = new();
}

public class Invoice
{
    [Key]
    public int Id { get; set; }
    [Display(Name ="Invoice Number")]
    public string InvNumber { get; set; }
    [Display(Name = "Invoice Amount")]
    public decimal InvAmount { get; set; }
    [Display(Name = "Issued? (Yes/No)")]
    public bool InvIssued { get; set; } = false;
    [Display(Name = "Paid? (Yes/No)")]
    public bool InvPaid { get; set; } = false;

    public int CustomerId { get; set; }
}

我设置它的方式是一对多关系。现在,两个相关的问题是,在发票的Create表单中,我还需要输入CustomerId,否则我会得到SQL异常错误。但是,我一直不知道如何将数据绑定到Customer表,以便检索可用客户的列表,并将其作为创建发票期间的一个选项。
我的.cshtml文件包含:

<div class="form-group">
            <label asp-for="Invoice.CustomerId" class="control-label"></label>
            <input asp-for="Invoice.CustomerId" class="form-control" value="3"/>
            <span asp-validation-for="Invoice.InvNumber" class="text-danger"></span>
        </div>

        <div class="form-group">
            <label asp-for="Invoice.InvNumber" class="control-label"></label>
            <input asp-for="Invoice.InvNumber" class="form-control" />
            <span asp-validation-for="Invoice.InvNumber" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Invoice.InvAmount" class="control-label"></label>
            <input asp-for="Invoice.InvAmount" class="form-control" />
            <span asp-validation-for="Invoice.InvAmount" class="text-danger"></span>
        </div>
 
        <div class="form-check">
            <input class="form-check-input" type="radio" name="InvIssued" id="InvIssued" value="true" checked="">
            <label class="form-check-label" asp-for="Invoice.InvIssued">
                The invoice has been issued.
            </label>
        </div>
        <div class="form-check">
            <input class="form-check-input" type="radio" name="InvNotIssed" id="InvNotIssed" value="false">
            <label class="form-check-label" asp-for="Invoice.InvIssued">
                The invoice has not been issued.
            </label>
        </div>
        
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
</div>

我的页面模型是:

public class AddInvoiceModel : PageModel
{
    private readonly InvoicesAppContext InvoiceContext;

    public AddInvoiceModel(InvoicesAppContext contextInvoices)
    {
        InvoiceContext = contextInvoices;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    [BindProperty]
    public Invoice Invoice { get; set; }

    // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

       InvoiceContext.Invoice.Add(Invoice);
       await InvoiceContext.SaveChangesAsync();

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

所以我的问题是

  • 如何在AddInvoice页面模型中添加对Customer表的引用?
  • CustomerIdint,而不是客户的实际名称。如何检索名称而不是ID?

谢谢大家的帮助。对不起,这些基本的东西。我还在学习。

8tntrjer

8tntrjer1#

在AddInvoiceModel中:

public class AddInvoiceModel : PageModel
    {
       private readonly InvoicesAppContext InvoiceContext;

       public AddInvoiceModel(InvoicesAppContext contextInvoices)
         {
           InvoiceContext = contextInvoices;
         }

        public SelectList CustomerOptions { get; set; }
        public IActionResult OnGet()
        {
            List<Customer> cities = new()
            {
                new Customer { Id = 1, CustomerName = "Latur" },
                new Customer { Id = 2, CustomerName = "Solapur" },
               
            };// you also can get data from database
            CustomerOptions = new SelectList(cities.Select(x => new SelectListItem
            {
                Value = x.Id.ToString(),
                Text = x.CustomerName
            }).ToList(), "Value", "Text");
            return Page();
        }

在cshtml文件中:

<div class="form-group">
            <label asp-for="Invoice.CustomerId" class="control-label"></label>
           <select asp-for="Invoice.CustomerId" class="form-control" asp-items="Model.CustomerOptions"></select>
            <span asp-validation-for="Invoice.CustomerId" class="text-danger"></span>
        </div>

结果:

gab6jxml

gab6jxml2#

通常,在创建发票时,您知道客户是谁,因此知道他们的ID。您可以将其分配给OnGet中的发票:

public IActionResult OnGet()
{
    Invoice = new Invoice{ CustomerId = id };
    return Page();
}

接下来的问题是将该ID添加到发票表单中,以便将其与发票的其余详细信息沿着发布。您可以将其作为隐藏字段添加到表单中:

<input asp-for="Invoice.CustomerId" type="hidden" />

如果您不知道客户是谁,则提供一个包含客户的选择列表,以便用户可以为发票选择一个。将select元素绑定到Invoice.CustomerId属性:

<select asp-for="Invoice.CustomerId" asp-items="Model.CustomerOptions"></select>

CustomerOptions是您在OnGet处理程序中填充的SelectList

public SelectList CustomerOptions { get; set; }
public async Task<IActionResult> OnGet()
{
    CustomerOptions = new SelectList(await db.Customers.Select(x => new SelectListItem{
        Value = x.CustomerId.ToString(),
        Text = x.CustomerName
    }).ToListAsync(), nameof(SelectListItem.Value), nameof(SelectListItem.Text));
    return Page();
}
af7jpaap

af7jpaap3#

试试这个:

public class Order
{
    public int OrderId { get; set; }
    public string Customer { get; set; }
    public List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
    public int OrderItemId { get; set; }
    public string Item { get; set; }
    public decimal Price { get; set; }
}
@page
@model CreateModel
@{
}
<form method="post">
    <input asp-for="Order.Customer" /><br />
    <input asp-for="Order.OrderItems[0].Item" /><br>
    <input asp-for="Order.OrderItems[0].Price" /><br>
    <input type="submit"/>
</form>
public class CreateModel : PageModel
{
    [BindProperty]
    public Order Order { get; set; }
    public void OnPost()
    {
    }
}

来源链接:https://www.learnrazorpages.com/razor-pages/model-binding

相关问题