[C#/ASP.NET MVC/.NETCORE] ViewComponent 클래스 : 데이터를 표시하는 뷰 컴포넌트 만들기
C#/ASP.NET MVC 2020. 10. 9. 00:21728x90
반응형
728x170
▶ Models/TestModel.cs
namespace TestProject.Models
{
/// <summary>
/// 테스트 모델
/// </summary>
public class TestModel
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Property
////////////////////////////////////////////////////////////////////////////////////////// Public
#region ID - ID
/// <summary>
/// ID
/// </summary>
public int ID { get; set; }
#endregion
#region 제목 - Title
/// <summary>
/// 제목
/// </summary>
public string Title { get; set; }
#endregion
}
}
728x90
▶ ViewComponents/TestListViewComponent.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using TestProject.Models;
namespace TestProject.ViewComponents
{
/// <summary>
/// 테스트 목록 뷰 컴포넌트
/// </summary>
public class TestListViewComponent : ViewComponent
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Public
#region 호출하기 - Invoke()
/// <summary>
/// 호출하기
/// </summary>
/// <returns>뷰 컴포넌트 결과</returns>
public IViewComponentResult Invoke()
{
List<TestModel> list = new List<TestModel>()
{
new TestModel { ID = 1, Title = "ASP.NET Core" },
new TestModel { ID = 2, Title = "Bootstrap" },
new TestModel { ID = 3, Title = "C#" },
new TestModel { ID = 4, Title = "Dapper" },
new TestModel { ID = 5, Title = "Azure" },
new TestModel { ID = 6, Title = "jQuery" },
new TestModel { ID = 7, Title = "Angular" }
};
return View(list);
}
#endregion
}
}
300x250
▶ Views/Shared/TestList/Default.cshtml
@model List<TestProject.Models.TestModel>
<ul>
@foreach(TestModel test in Model)
{
<li>@test.Title</li>
}
</ul>
▶ Controllers/TestController.cs
using Microsoft.AspNetCore.Mvc;
namespace TestProject.Controllers
{
/// <summary>
/// 테스트 컨트롤러
/// </summary>
public class TestController : Controller
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Public
#region 인덱스 페이지 처리하기 - Index()
/// <summary>
/// 인덱스 페이지 처리하기
/// </summary>
/// <returns>액션 결과</returns>
public IActionResult Index()
{
return View();
}
#endregion
}
}
▶ Views/Test/Index.cshtml
@{
Layout = null;
}
<p>ViewComponent 클래스 : 데이터를 표시하는 뷰 컴포넌트 만들기</p>
<hr />
@await Component.InvokeAsync("TestList")
728x90
반응형
그리드형(광고전용)
댓글을 달아 주세요