Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace MyLibrary.App.Pages.Books
- {
- using Data;
- using MyLibrary.Models;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.AspNetCore.Mvc.RazorPages;
- using Microsoft.AspNetCore.Mvc.Rendering;
- using System;
- using System.Threading.Tasks;
- public class BorrowModel : PageModel
- {
- private readonly MyLibraryDbContext context;
- public BorrowModel(MyLibraryDbContext context)
- {
- this.context = context;
- }
- [BindProperty]
- public int Id { get; set; }
- [BindProperty]
- public int BorrowerId { get; set; }
- [BindProperty]
- public DateTime BorrowDate { get; set; }
- [BindProperty]
- public DateTime ReturnDate { get; set; }
- public BookBorrower BookBorrower { get; set; }
- public IActionResult OnGet(int id)
- {
- InitializeBorrowers();
- return Page();
- }
- public async Task<IActionResult> OnPostAsync()
- {
- this.BookBorrower = new BookBorrower()
- {
- BookId = this.Id,
- BorrowerId = this.BorrowerId,
- BorrowDate = this.BorrowDate,
- ReturnDate = this.ReturnDate
- };
- if (!this.ModelState.IsValid)
- {
- InitializeBorrowers();
- return Page();
- }
- try
- {
- this.context.BookBorrowers.Add(this.BookBorrower);
- await this.context.SaveChangesAsync();
- var book = this.context.Books.Find(Id);
- book.IsBorrowed = true;
- await this.context.SaveChangesAsync();
- this.TempData["Success"] = $@"You land book ""{this.BookBorrower.Book.Title}"" to a frend!";
- }
- catch (Exception e)
- {
- this.TempData["Success"] = "Unsuccessfull operation!";
- InitializeBorrowers();
- return Page();
- }
- return RedirectToPage("/Index");
- }
- private void InitializeBorrowers()
- {
- this.ViewData["BorrowerId"] = new SelectList(this.context.Borrowers, "Id", "Name");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement