简体   繁体   English

如何为 Razor Pages (.NET Core) 绑定视图模型?

[英]How to bind view model for Razor Pages (.NET Core)?

Let's say I have this view model.假设我有这个视图模型。 Bear in mind, this is a view model.请记住,这是一个视图模型。 Not the domain/entity model.不是域/实体模型。

public class Cart
{
    public string Name { get; set; }
    public int Qty { get; set; }
    public decimal Price { get; set; }
    public decimal TotalPrice { get; set; }

}

How do I scaffold to create CRUD Razor Page ?如何搭建脚手架以创建 CRUD Razor 页面?

Here is a demo ,you could refer to :这是一个演示,您可以参考:

OrderItem Entity model and Cart View model, the View Model is related to the presentation layer of our application. OrderItem Entity 模型和Cart View 模型,View Model 关系到我们应用的表现层。 They are defined based on how the data is presented to the user rather than how they are stored.它们是根据数据如何呈现给用户而不是如何存储来定义的。

 public class OrderItem
{
    public int Id { get; set; }
    public int Qty { get; set; }
    public decimal Price { get; set; }
    public decimal TotalPrice { get; set; }

    public Product Product { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
}
public class Cart
{
    public string Name { get; set; }
    public int Qty { get; set; }
    public decimal Price { get; set; }
    public decimal TotalPrice { get; set; }
}

 public class RazorPagesDbContext:DbContext
{
    public RazorPagesDbContext(DbContextOptions<RazorPagesDbContext> options):base(options)
    { }

    public DbSet<Product> Product { get; set; }
    public DbSet<OrderItem> OrderItem { get; set; }
}

The CreateOrder Razor Page CreateOrder Razor 页面

@page
@model RazorPages2_2.Pages.Carts.CreateOrderModel
@{
  ViewData["Title"] = "CreateOrder";
}
<h1>CreateOrder</h1>

<hr />
<div class="row">
  <div class="col-md-4">
    <form method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="Cart.Name" class="control-label"></label>
            <input asp-for="Cart.Name" class="form-control" />
            <span asp-validation-for="Cart.Name" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Cart.Price" class="control-label"></label>
            <input asp-for="Cart.Price" class="form-control" />
            <span asp-validation-for="Cart.Price" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Cart.Qty" class="control-label"></label>
            <input asp-for="Cart.Qty" class="form-control" />
            <span asp-validation-for="Cart.Qty" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Cart.TotalPrice" class="control-label"></label>
            <input asp-for="Cart.TotalPrice" class="form-control" />
            <span asp-validation-for="Cart.TotalPrice" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-primary" />
        </div>
    </form>
  </div>
</div>

<div>
  <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

The CreateOrder page model, the Cart property uses the [BindProperty] attribute to opt-in to model binding.在 CreateOrder 页面模型中, Cart属性使用 [BindProperty] 属性来选择加入模型绑定。 When the Create form posts the form values, the ASP.NET Core runtime binds the posted values to the Cart model then put the values into the entity model.当 Create 表单发布表单值时,ASP.NET Core 运行时将发布的值绑定到Cart模型,然后将这些值放入实体模型中。

public class CreateOrderModel : PageModel
{
    private readonly RazorPagesDbContext _context;

    public CreateOrderModel(RazorPagesDbContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
        var product = _context.Product.FirstOrDefault();
        Cart = new Cart
        {
            Name = product.ProductName,
            Price = product.Price,
            Qty = 2,
            TotalPrice = product.Price * 2
        };
        return Page();
    }

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

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        var product = _context.Product.SingleOrDefault(p => p.ProductName == Cart.Name);
        OrderItem orderItem = new OrderItem
        {

            Price = Cart.Price,
            Qty = Cart.Qty,
            TotalPrice = Cart.TotalPrice,
            Product = product
        };
        _context.OrderItem.Add(orderItem);
        await _context.SaveChangesAsync();

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

Result:结果: 在此处输入图片说明 You could refer to the offocial doc about the Razor pages to create the page you want .您可以参考有关 Razor 页面的官方文档来创建您想要的页面。

CODE BEHIND :代码隐藏:

public class IndexModel : PageModel
    {

        private readonly ApplicationDbContext _db;
        public IndexModel(ApplicationDbContext db)
        {
            _db = db;

        }

        public IEnumerable<Cart> Carts { get; set; }

        public async Task OnGet()
        {
            Books = await _db.Carts.ToListAsync();
        }
    }

You need :你需要 :

  public class ApplicationDbContext:DbContext
        {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
            {

            }

            public DbSet<Cart> carts { get; set; }
        }

for the View :对于视图:

@model CardList.IndexModel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 .net 核心 razor 页面中绑定复选框? - How do you bind a checkbox in .net core razor pages? Asp .net Core:如何在Razor Pages的Partial View中使用模型? - Asp .net Core : How can I use a model inside a Partial View in Razor Pages? ASP .NET Core 5 Razor 页面:如何正确使用局部视图并验证它的 model Z9ED39E28EA931586B76A - ASP .NET Core 5 Razor Pages: how to properly use Partial View and validate it's model state? 如何检查 razor 视图是否存在,但在 ASP.NET 核心 Razor 页面中? - How to check if a razor view exists, but in ASP.NET Core Razor Pages? 返回视图(模型:MyModel); 相当于 ASP.Net Core Razor Pages - return View(model: MyModel); equivalent in ASP.Net Core Razor Pages 使用 .NET Core Razor 页面(非 MVC)中视图模型的选择标记助手创建下拉列表 - Create dropdownlist using select tag helper of a view model in .NET Core Razor Pages (Not MVC) Asp.Net-Core with Razor Pages 绑定隐藏输入 - Asp.Net-Core with Razor Pages Bind hidden input 如何将 razor 视图与对象列表绑定到 model? - How to bind razor view to model with list of objects? 如何在 .NET Core Razor 页面中按日期搜索? - How to search by date in .NET Core Razor pages? Model 绑定在 ASP.NET 核心 Razor 页 - Model Binding in ASP.NET Core Razor Pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM