nopcommerce里面的@Html.Widget("home_page_top") 是什么?

时间:2022-08-02 22:45:50

很多朋友在修改模板的时候看到很多类似@Html.Widget("xxx")的东西,这里简单介绍一下流程:

比如@Html.Widget("home_page_top"),首先要知道Html.Widget是什么,这是Html的一个扩展方法,位于Nop.Web.Framework\HtmlExtensions.cs

public static MvcHtmlString Widget(this HtmlHelper helper, string widgetZone)
{
return helper.Action("WidgetsByZone", "Widget", new { widgetZone = widgetZone });
}

可以看到这里面调用的是action,找到WidgetController下面的WidgetsByZone,这是一个child action(不懂的百度一下),读一下代码,就能了解这个方法就是通过反射获取到实现接口IWidgetPlugin并且GetWidgetZones()包含home_page_top的插件的列表,然后创建一个model传递给试图:

[ChildActionOnly]
public ActionResult WidgetsByZone(string widgetZone)
{
//model
var model = new List<RenderWidgetModel>(); var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, _storeContext.CurrentStore.Id);
foreach (var widget in widgets)
{
var widgetModel = new RenderWidgetModel(); string actionName;
string controllerName;
RouteValueDictionary routeValues;
widget.GetDisplayWidgetRoute(widgetZone, out actionName, out controllerName, out routeValues);
widgetModel.ActionName = actionName;
widgetModel.ControllerName = controllerName;
widgetModel.RouteValues = routeValues; model.Add(widgetModel);
} return PartialView(model);
}

打开试图Widget\WidgetsByZone.cshtml:

@model List<RenderWidgetModel>
@using Nop.Web.Models.Cms;
@foreach (var widget in Model)
{
@Html.Action(widget.ActionName, widget.ControllerName, widget.RouteValues)
}

这个试图的目的就是循环输出html,具体输出的内容在插件里面实现的,比如插件Nop.Plugin.Widgets.NivoSlider里面有个NivoSliderPlugin,这类插件必须继承自BasePlugin,和IWidgetPlugin,里面的方法GetDisplayWidgetRoute就是用于返回显示这个插件内容的action的信息,WidgetsNivoSliderController.cs里面的public ActionResult PublicInfo(string widgetZone)就是这个插件具体输出的内容,大体流程就是这样了。

分享是一种美。版权所有,转载请注明出处 http://www.nopchina.net/