简体   繁体   中英

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 ?

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

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM