Back To Home

Name: Ngày 21: Truy xuất dữ liệu qua Glass Mapper / Model Binding

🎯 Ngày 21: Truy xuất dữ liệu qua Glass Mapper / Model Binding

Glass.Mapper là ORM dành cho Sitecore, giúp map field trong item → property C# và bind thẳng vào View mà không cần truy vấn thủ công bằng Sitecore.Context.Item hoặc item.Fields[].


⭐ 1. Glass Mapper là gì?

Glass.Mapper.Sc là một library giúp:

✔ Mapping item → C# model
✔ Truy cập field bằng property mạnh kiểu (string, int, DateTime, Image…)
✔ Tự động xử lý Datasource item
✔ Hỗ trợ Lazy Loading, Infer Template
✔ Hỗ trợ Dependency Injection

Không cần:

 
var item = Sitecore.Context.Item; item["Title"]; item.Fields["Image"].Value;

Mà chỉ cần:

 
var model = _context.GetCurrentItem<IHomePage>(); var title = model.Title; var image = model.BannerImage;

⭐ 2. Cài đặt Glass Mapper

Trong Sitecore XP 9+ bạn dùng:

 
Install-Package Glass.Mapper.Sc.Mvc

Hoặc dùng Foundation project đã tích hợp.


⭐ 3. Cấu hình GlassMapper (Glass.Mapper.Sc)

Trong Foundation, thường có file:

 
App_Start/GlassMapperSc.cs

Trong đó config DI:

 
public static void CastleConfig(IWindsorContainer container) { container.Install(new SitecoreInstaller()); }

GlassMapper sẽ tự map model.


⭐ 4. Định nghĩa Model trong Glass

Ví dụ: Template "Home Page" có field:

  • Title (Single Line Text)

  • BannerImage (Image)

  • Content (Rich Text)

Bạn tạo model:

 
[SitecoreType(AutoMap = true)] public interface IHomePage { [SitecoreId] Guid Id { get; } [SitecoreField] string Title { get; set; } [SitecoreField] Image BannerImage { get; set; } [SitecoreField] string Content { get; set; } }

✔ Chỉ dùng AutoMap
✔ Không cần chỉ TemplateId vì Glass tự map theo field name


⭐ 5. Lấy dữ liệu trong Controller

 
public class HomeController : Controller { private readonly IGlassHtml _glassHtml; private readonly ISitecoreContext _context; public HomeController( IGlassHtml glassHtml, ISitecoreContext context) { _glassHtml = glassHtml; _context = context; } public ActionResult Index() { var model = _context.GetCurrentItem<IHomePage>(); return View(model); } }

GlassMapper tự map đúng item theo URL.


⭐ 6. Binding trong View

 
@model IHomePage <h1>@Model.Title</h1> <div> @Html.Glass().Editable(Model, x => x.Content) </div> <div> @Html.Glass().RenderImage(Model, x => x.BannerImage) </div>

✔ Hỗ trợ Enjoy Editable trong Experience Editor
✔ Không cần HTML Helper phức tạp


⭐ 7. Truy xuất Datasource item

Nếu Rendering có Datasource:

 
var model = _context.GetRenderingItem<IHeroBanner>();

Hoặc Glass có extension:

 
var model = RenderingContext.Current.Rendering.Item.GlassCast<IHeroBanner>();

⭐ 8. Query item bằng Glass

 
var children = _context.GetChildren<INewsItem>(model);

Hoặc query bằng SitecoreService:

 
var service = new SitecoreService("web"); var item = service.GetItem<IArticle>("/sitecore/content/Article 1");

⭐ 9. Field Type Mapping

Glass hỗ trợ nhiều field type:

Sitecore Field Glass Type
Single Line Text string
Rich Text string
Number int/double
Checkbox bool
Image Glass.Mapper.Sc.Fields.Image
General Link Glass.Mapper.Sc.Fields.Link
Multilist IEnumerable<TModel>
Droplink TModel

Ví dụ multilist:

 
[SitecoreField] IEnumerable<IProduct> Products { get; set; }

⭐ 10. Ưu điểm của Glass Mapper

✔ Code sạch, strongly typed

✔ Dễ debug

✔ Hỗ trợ Experience Editor

✔ Inject bằng DI

✔ Dễ maintain

✔ Không phải parse field bằng string


⭐ 11. Nhược điểm

  • Performance hơi thấp nếu load nhiều item (vì nó map từng field → property)

  • Không phù hợp cho batch import nặng

  • Cần cẩn thận khi dùng AutoMap


⭐ 12. Khi nào nên dùng Glass?

Trường hợp Có nên dùng
Rendering MVC ✔ Nên dùng
Page-level model
SXA JSON API ❌ Không
Import hàng loạt ❌ Không
Custom service data ❌ Không

🎉 Tổng kết Ngày 21

Hôm nay bạn học:

  • Glass Mapper là gì

  • Cách tạo model và map field

  • Cách lấy data qua ISitecoreContext

  • Binding trong view bằng Html.Glass()

  • Truy xuất datasource item

  • Query với SitecoreService

  • Best practices và lưu ý

Donald Trump

Để trở thành người chiến thắng, bạn cần biết khi nào là đủ. Đôi khi trong cuộc sống, bạn phải từ bỏ cuộc chiến và chuyển sang mục tiêu mới mang lại hiệu quả hơn

Related Post