ASP.NET Core Razor Pages模型绑定

huangapple go评论62阅读模式
英文:

ASP.NET Core Razor Pages model binding

问题

我希望理解您的问题正确:您想知道如何在AddInvoice页面模型中添加对Customer表的引用,并且如何检索客户的名称而不是ID。以下是您的问题的翻译:

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

谢谢您的帮助。对于这些基础知识的问题,我还在学习中,希望您能理解。

英文:

I'm pretty new with ASP.NET Core Razor Pages and I would like your help on the following.

I have the following two classes:

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();
}

and

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; }
}

The way I've set it up is for a one-to-many relationship. Now, two related issues are that during the Create form for an invoice I also need to input a CustomerId, otherwise I get an SQL exception error. However, for the life of me, I can't figure out how to bind the data, to the Customer table, so that I can retrieve the list of available customers and have it as an option during the creation of an invoice.

My .cshtml file contains:

       <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>

and my page model is:

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");
    }
}

So my questions are:

  • How do I add a reference to Customer table in the AddInvoice Page Model?
  • The CustomerId is an int and not the actual name of the customer. How do I retrieve the names and not the id?

Thank you all for your help. And sorry for this basic stuff. I am still learning.

答案1

得分: 1

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

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

然后,您需要将该ID添加到发票表单中,以便与其他发票详细信息一起提交。您可以将其添加到表单作为一个隐藏字段:

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

如果您不知道客户是谁,您可以提供一个包含客户的选择列表,以便用户可以为发票选择一个客户。您将选择元素绑定到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();
}
英文:

Usually, when creating an invoice, you know who the customer is, and therefore their ID. You assign this to the Invoice in OnGet:

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

It's then a question of adding that ID to the invoice form so that it is posted along with the rest of the invoice details. You'd add it to the form as a hidden field:

&lt;input asp-for=&quot;Invoice.CustomerId&quot; type=&quot;hidden&quot; /&gt;

If you don't know who the customer is, you provide a select list containing customers so that the user can select one for the invoice. You bind the select element to the Invoice.CustomerId property:

&lt;select asp-for=&quot;Invoice.CustomerId&quot; asp-items=&quot;Model.CustomerOptions&quot;&gt;&lt;/select&gt;

The CustomerOptions is a SelectList that you populate in the OnGet handler:

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

答案2

得分: 1

以下是您提供的代码的中文翻译部分:

在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" },
        };// 你也可以从数据库获取数据
        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>

结果:

ASP.NET Core Razor Pages模型绑定

英文:

In the AddInvoiceModel:

 public class AddInvoiceModel : PageModel
    {
       private readonly InvoicesAppContext InvoiceContext;

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

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

In cshtml file:

       &lt;div class=&quot;form-group&quot;&gt;
            &lt;label asp-for=&quot;Invoice.CustomerId&quot; class=&quot;control-label&quot;&gt;&lt;/label&gt;
           &lt;select asp-for=&quot;Invoice.CustomerId&quot; class=&quot;form-control&quot; asp-items=&quot;Model.CustomerOptions&quot;&gt;&lt;/select&gt;
            &lt;span asp-validation-for=&quot;Invoice.CustomerId&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
        &lt;/div&gt;

result:

ASP.NET Core Razor Pages模型绑定

答案3

得分: 0

尝试这个:

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

链接到源代码: https://www.learnrazorpages.com/razor-pages/model-binding

英文:

Try this:

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

Link to source: https://www.learnrazorpages.com/razor-pages/model-binding

huangapple
  • 本文由 发表于 2023年6月29日 17:11:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定