ما هي View Components
-
بنتعرف في هذا الدرس على View Components والتي يمكن تعريفها على انها C# classes بحيث يمكن استدعاؤها من View. تساعد View Components في دعم Views من خلال تزويدهم بالبيانات. وبالتالي تساعد في تضمين واستخدام محتويات معقدة في Views.
بعض الأمثلة حيث يمكنك استخدام View Components هي:
- لوحات المصادقة Authentication Panels في المواقع التي يمكن للمستخدمين من خلالها تسجيل الدخول دون زيارة صفحة منفصلة..
- إنشاء نظام ملاحة navigation ديناميكي للموقع يتغير حسب دور المستخدم.
- Shopping Cart panels التي تعرض المنتجات الموجودة حاليًا في سلة التسوق.
تمام وحتي نفهم الموضوع وكالعاده نبدأ بتطبيق مثال:
انشاء View Component
View Components هي مجرد C# classes مشتقة من ViewComponent class المعرفة في Microsoft.AspNetCore.Mvc namespace.
يجب أن يحتوي View Component على Method باسم ()Invoke والي بتعمل على إرجاع بعض أشكال البيانات إلىView.
يمكن إنشاء View Component في أي مكان في التطبيق ولكن وفقًا لconventions، يجب إنشاؤها داخل مجلد Components الموجود في root folder للتطبيق.
لإنشاء View Component يجب انشاء مجلد باسم Components في المشروع، لذا انقر بزر الماوس الأيمن فوق project file وحدد Add ➤ New Folder ثم قم بتسمية هذا المجلد باسم Components. ثم انشى class داخل هذا المجلد وقم بتسميته Cart.cs. وما تنسى اشتقاق هذه class من class الأساسية المسميه ViewComponent، وبعدها بنضف Invoke method إليها. الكود التالي يوضح ذلك:
المثال الي بنعملو الان هو فكره بسيطة لكيفية تطبيق سلة المشتريات في التطبيق
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Components
{
public class Cart : ViewComponent
{
public string Invoke()
{
return "This is from View Component";
}
}
}
@await Component.InvokeAsync("NameofViewComponent")
@await Component.InvokeAsync("Cart")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - StudentsAcademy</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">StudentsAcademy</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
@await Component.InvokeAsync("Cart")
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2021 - StudentsAcademy - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

النوع في ViewComponent | Types الي بترجع |
ContentViewComponentResult | تستخدم لارجاع انع encoded HTML. مثل: Content("<h2>some text</h2>") |
HtmlContentViewComponentResult | تستخدم لارجاع انع without encoding.
مثل HtmlContentViewComponentResult("<h2>some text</h2>") |
ViewViewComponentResult | تستخدم لارجاع انع Partial View with optional view model data.
مثل: View("NameofView") |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Components
{
public class Cart : ViewComponent
{
//public string Invoke()
//{
// return "This is from View Component, ";
//}
public IViewComponentResult Invoke()
{
return Content("This is from <h2>View Component</h2>");
}
}
}
Content("This is from <h2>View Component</h2>")


using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Components
{
public class Cart : ViewComponent
{
//public string Invoke()
//{
// return "This is from View Component, ";
//}
//public IViewComponentResult Invoke()
//{
// return Content("This is from <h2>View Component</h2>");
//}
public IViewComponentResult Invoke()
{
return new HtmlContentViewComponentResult(new HtmlString("This is from <h2>View Component</h2>"));
}
}
}

View(); // Call default partial view
View(model); // Call default partial view and send model to it
View("ViewName"); // Call partial view by name
View("ViewName ", model); // Call partial view by name and send model to it.
/Views/{controller}/Components/{view component}/{partial view name}
/Views/Shared/Components/{view component}/{partial view name}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Models
{
public class CoursesModel
{
public string CourseNumber { get; set; }
public string CourseName { get; set; }
public string CourseDescription { get; set; }
public decimal Price { get; set; }
public int Capacity { get; set; }
}
}
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using StudentsAcademy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Components
{
public class Cart : ViewComponent
{
public IViewComponentResult Invoke()
{
CoursesModel[] Couurses = new CoursesModel[] {
new CoursesModel() { CourseNumber = "0001",CourseName="Math",CourseDescription="Math Desc",Capacity=20, Price = 115 },
new CoursesModel() { CourseNumber = "0002",CourseName="Sciences",CourseDescription="Sciences Desc",Capacity=30, Price = 120 },
new CoursesModel() { CourseNumber = "0003",CourseName="Physics",CourseDescription="Physics Desc",Capacity=25, Price = 140 },
};
return View(Couurses);
}
}
}

/Views/Home/Components/Cart/Default.cshtml
/Views/Shared/Components/Cart/Default.cshtml

@model CoursesModel[]
<table style="width:50%">
<tr>
<td><u>Product Name</u></td>
<td><u>Price</u></td>
</tr>
@{
foreach (CoursesModel p in Model)
{
<tr>
<td>@p.CourseNumber</td>
<td>@p.CourseName</td>
<td>@p.CourseDescription</td>
<td>@p.Price</td>
</tr>
}
}
</table>
https://localhost:44382/

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using StudentsAcademy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Components
{
public class Cart : ViewComponent
{
public IViewComponentResult Invoke()
{
CoursesModel[] Couurses = new CoursesModel[] {
new CoursesModel() { CourseNumber = "0001",CourseName="Math",CourseDescription="Math Desc",Capacity=20, Price = 115 },
new CoursesModel() { CourseNumber = "0002",CourseName="Sciences",CourseDescription="Sciences Desc",Capacity=30, Price = 120 },
new CoursesModel() { CourseNumber = "0003",CourseName="Physics",CourseDescription="Physics Desc",Capacity=25, Price = 140 },
};
return View("Default",Couurses.Sum(o => o.Price).ToString());
}
}
}
return View("Default",Couurses.Sum(o => o.Price).ToString());
@model string
Total Cart (@Model)
https://localhost:44382/

string target = RouteData.Values["id"]
اترك تعليقك