Articles → ASP.NET CORE → Add data in the table in asp.net core

Add data in the table in asp.net core






Scenario




Picture showing the schema of the Book table

Click to Enlarge




Code






@page 
@model BookManagementSystem.Pages.Books.CreateModel
<div class="border container" style="padding:30px">
	<form method="post">
		<div class="form-group row">
			<div class="col-4">
				<label asp-for="MyBook.Name"></label>
			</div>
			<div class="col-6">
				<input asp-for="MyBook.Name" class="form-control" />
			</div>
		</div>
		<div class="form-group row">
			<div class="col-4">
				<label asp-for="MyBook.Author"></label>
			</div>
			<div class="col-6">
				<input asp-for="MyBook.Author" class="form-control" />
			</div>
		</div>
		<div class="form-group row">
			<div class="col-4">
				<input type="submit" value="Create" class="btn btn-primary form-control" />
			</div>
		</div>
	</form>
</div>




using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookManagementSystem.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace BookManagementSystem.Pages.Books {
  public class CreateModel: PageModel {
    private readonly ApplicationDbContext _db;

    public CreateModel(ApplicationDbContext db) {
        _db = db;
      }
      [BindProperty]
    public Book MyBook {
      get;
      set;
    }
    public void OnGet() {

    }

    public async Task < IActionResult > OnPost() {
      if (ModelState.IsValid) {
        await _db.Book.AddAsync(MyBook);
        await _db.SaveChangesAsync();
        return RedirectToPage("Books");
      } else {
        return Page();
      }
    }
  }
}





Output




Picture showing the screen to enter the book data

Click to Enlarge



Picture showing the screen to list down all the books

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, April 1, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250