0% found this document useful (0 votes)
27 views

MVC Asp - Net Core Summary Practical

The document discusses various aspects of building a web application including handling query strings in URLs, working with cookies, creating database models and context, performing CRUD operations, and building search functionality to retrieve data from the database based on title or category.

Uploaded by

Maryam Waleed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

MVC Asp - Net Core Summary Practical

The document discusses various aspects of building a web application including handling query strings in URLs, working with cookies, creating database models and context, performing CRUD operations, and building search functionality to retrieve data from the database based on title or category.

Uploaded by

Maryam Waleed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Quary string

Create action describe Query String in URL:

Check null

Another
example

Cookies

Create HttpContext.Response.Cookies.Append(“Lang", “English”);


var options = new CookieOptions { Expires = DateTime.Now.AddDays(15) };
To set cookie HttpContext.Response.Cookies.Append(“Lang", “English”, options);
options: This cookie is created as a non-persistent cookie and expires in 15 days.
To delete a cookie, set it’s expiry date to a past date
Expires = DateTime.Now.AddDays(-1)
if (Request.Cookies[“cookiename"] != null)
read a cookie {
value string val = Request.Cookies[“cookiename"];
}
Database Connection :

Create Model Classes

[Key] Primary key column

[Required] NOT NULL constraint

maximum characters of a string


[StringLength(50)]

You may explicitly set the ForeignKey annotation for the Collection
[ForeignKey]
attribute (this is optional

Create a Database Context Class


public class AppDbContext : DbContext
{ public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{}
//complete the code below to create the Books and Reviews table
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

builder.Entity<Category>().HasData(new Category { CategoryID = 1, CategoryName = "Technology" });


Return all book from database var booksList =ctx.Books.ToList();
Where condition

Book BY Title in Search Controller By categories in Search Controller


public IActionResult BookByTitle(string? title) public IActionResult BookByCategory(int? catID)
{ { // no catID will be provided
if (String.IsNullOrEmpty(title)) if (catID == null || catID == 0)
{ { //to display a dropdown list
// no title provided, display the view var categoriesList = new SelectList(ctx.Categories.ToList(), "CategoryID",
return View(); "CategoryName");
} ViewBag.CatList = categoriesList;
//when a title is provided retrieve the books return View();
var books = ctx.Books }
.Where(b => b.Title.Contains(title)) //when ID provided read books that contain the title and return the result
.Include(b => b.Category) //get category details var books = ctx.Books
.ToList(); .Where(b => b.CategoryID == catID)
//return View(books); .Include(b => b.Category) // get category details
return PartialView("_PartialSearchResult", books); .ToList();
return PartialView("_PartialSearchResult", books); }
}}

Book BY Title Razor By categories Razor


<h1>Search By Title</h1> h1>Search By Category</h1>
<p>This page was loaded on @DateTime.Now</p> <p>This page was loaded on @DateTime.Now</p>
<form method="get"> <form id="searchForm" method="get">
<label> Book title</label> <select id="CategoryID" asp-items=ViewBag.CatList>
<input type="text" required name="title" id="txtTitle" /> <option value="0">Select a category</option>
<button type="button" class="btn btn-primary" </select>
id="btnSearch">Search</button> <button type="button" class="btn btn-primary"
</form> id="btnSearch">Search</button>
//---------------------------------------------------- </form>
<div id="searchResults"> </div> //----------------------------------------------------
//---------------------------------------------------- <!-- partial view will be loaded here-->
<script type="text/javascript"> <div id="searchResults"></div>
$(document).ready(function() { //----------------------------------------------------
$("#btnSearch").click(function() { <script type="text/javascript">
//get title of the selected item in the select list $(document).ready(function() {
var searchVal = $("#txtTitle").val(); $("#btnSearch").click(function() {
/*call action and pass the title as a parameter*/ //get CategoryID value of the selected item in the select
$("#searchResults").load("/Search/BookByTitle", { title: list
searchVal });});}); var searchVal = $("#CategoryID").val();
</script> /*call Action and pass the Cateogry ID of the select list*/
$("#searchResults").load("@Url.Action("BookByCategory")", {
catID: searchVal });
});});</script>

VIEW or Detials method


in Search Controller Razor Page
public IActionResult Detail(int? id) <h1>Book Detail</h1>
{ <div class="card-deck">
if (id == null) <div class="row">
{ <div class="col-md-12">
return BadRequest(); <div class="card">
} <div class="card-header">
//eager loading <h5>@Model.Title</h5>
Book book = ctx.Books </div>
.Where(b => b.BookID == id) <p class="card-text">
.Include(b => b.Category) //join with Category table Category: @Model.Category.CategoryName <br/>
.Include(b => b.Reviews) //Join with Reviews table Reviews: @Model.Reviews.Count
.FirstOrDefault(); Rating:@(Model.Reviews.Count > 0 ? Model.Reviews.Average(r =>
if (book == null) r.Rating):" None")
{ </p>
return NotFound(); <div>
} <img src=@("/images/"+Model.CoverPhoto) style="width:150px;
//view is returned only when there is a record to display float:left; margin-right:10px"/>
return View(book); <p>Author: @Model.Author</p>
<p>Published in: @Model.PublicationYear</p>
} <p>@Model.Description</p>
</div>
</div>
</div>
</div>
</div>

<h5>Reviews</h5>
@if (Model.Reviews.Count > 0)
{
<partial name="_PartialAllReviews" model="Model.Reviews" />
}
else
{
<p>There are no reviews for this book</p>
Get Request
Create&ADD Update&Edit Delete &Remove
[HttpGet] [HttpGet] [HttpGet]
public IActionResult Create() public IActionResult Edit(int? id) public IActionResult Delete(int? id)
{ { {
var categoriesList = new if (id == null) if (id == null)
SelectList(ctx.Categories.ToList(), "CategoryID", return BadRequest(); return BadRequest();
"CategoryName"); Book bk =ctx.Books.Find(id); Book bk =ctx.Books.Find(id);
ViewBag.CatList = categoriesList;
return View(); if (bk == null) if (bk == null)
} return NotFound(); return NotFound();
return View(bk);-> display html return View(bk);-> display html
} }

Post Request
Create&ADD Update&Edit Delete &Remove
[HttpPost] [HttpPost] [HttpPost]
public IActionResult Create(Book book) public IActionResult Upadate(Book public IActionResult Delete(Book book)
{ book) {
if (ModelState.IsValid){ {
ctx.Books.Add(book); if (ModelState.IsValid){ ctx.Books.Remove(book);
ctx.SaveChanges(); ctx.Books.Update(book); ctx.SaveChanges();
return Redirect("/Search/Detail/" + ctx.SaveChanges(); return Redirect("/Search/SearchByCategory/");
book.BookID); } return Redirect("/Search/Detail/" + }
book.BookID); }

Razor
<h1>New Book</h1> <-same change red highlight thing Kind of the same red highlight thing
<div class="row">
<div class="col-md-4">
<form enctype="multipart/form-data" asp-
controller="Book" asp-action="Create" method="post">
<div asp-validation-summary="All" class="text-
danger"></div>
<div class="form-group">
<label asp-for="CategoryID" class="control-
label"></label>
<select asp-for="CategoryID" asp-
items=ViewBag.CatList class="form-control">
<option value="">Select a category</option>
</select>
<span asp-validation-for="CategoryID" class="text-
danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-
danger"></span>
</div>

<div class="form-group">
<label asp-for="Description" class="control-
label"></label>
<textarea rows="6" cols="50" asp-for="Description"
class="form-control"></textarea>
<span asp-validation-for="Description" class="text-
danger"></span>
</div>
</form>

_PartialSearchResult.cshtml
<div class="row">
@if (Model.Count > 0) //check if the Model (list of books) has any books
{
foreach (var book in Model) // loop through each book in the model
{<div class="col-sm-3">
<div class="card" style="margin-bottom:15px; margin-top:10px">
<div class="card-header">
<h5>@book.Title</h5>
</div>
<p class="card-text">
Category: @book.Category.CategoryName
</p>
<img class="card-img-top" src=@("/images/"+book.CoverPhoto) style="width:100%;height:250px"/>
<div class="card-footer text-center">
<a asp-controller="Search" asp-action="Detail" asp-route-id=@book.BookID class="btn btn-primary">View</a>
<a asp-controller="Book" asp-action="Edit" asp-route-id=@book.BookID class="btn btn-primary">Edit</a>
<a asp-controller="Book" asp-action="Delete" asp-route-id=@book.BookID class="btn btn-danger">Delete</a>
</div>
</div>
</div>
}}
else
{ <p>No books found</p> }</div>

You might also like