项目中用到了viewcomponent 这里就来记录下
view页面调用组件示例
@await Component.InvokeAsync("RandomAdvert", new { advertGroup = "666", advertType = "1", size = 3 })
参数说明
RandomAdvert为组件名称
new { advertGroup = "666", advertType = "1", size = 3 }为参数
项目组件架构
image.png
控制器文件夹 ViewComponents
视图文件夹 View/Shared/Components/组件名称
控制器:名 + ViewComponent
视图:Default.cshtml为默认查找的视图,若自定义视图名,在需要在ViewComponent控制器中返回时指定该视图即可 return View("AdvertRandom");
项目中用到的控制器RandomAdvertViewComponent.cs
public class RandomAdvertViewComponent: ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string advertGroup, string advertType, int size)
{
ViewBag.advertGroup = advertGroup;
ViewBag.advertType = advertType;
ViewBag.Size = size;
return View("AdvertRandom");//自定义视图,所以需要返回视图名称
}
}
项目中用到的视图组件AdvertRandom.cshtml
<div class="" id="viewcomponentadvert">
</div>
<script>
$.ajax({
type: 'get',
url: apiUrl + '/api/Advert/GetAdvertByRandom',
data: {advertGroup:@ViewBag.advertGroup, advertType:@ViewBag.advertType,size:@ViewBag.size},
success: function (data, status) {
//省略...
}
})
</script>
网友评论