In this article, you will see how to use controllers and views base on a simple example of a configuration page in your plugin.
Firstly create Views directory and add a new file called _ViewImports.cshtml, then add content (simple copy and paste):
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Grand.Web.Common
@addTagHelper *, Grand.Web
@using Microsoft.AspNetCore.Mvc.ViewFeatures
@using Grand.Infrastructure.Extensions
@using Grand.Web.Common
@inject Grand.Web.Common.Localization.LocService Loc
This file is important because add tags helpers, and using for all your views
Next, create Controllers directory, then controller file :
[AuthorizeAdmin]
[Area("Admin")]
public class MyPluginController : BasePluginController
{
private readonly ISettingService _settingService;
private readonly MyPluginSettings _myPluginSettings;
public MyPluginController(ISettingService settingService,MyPluginSettings myPluginSettings)
{
_settingService = settingService;
_myPluginSettings = myPluginSettings;
}
[HttpGet]
public IActionResult Configure()
{
var model = new SettingsModel() {
ApiKey = _myPluginSettings.ApiKey,
UseSandbox = _myPluginSettings.UseSandbox
};
return View("~/Plugins/Misc.MyPlugin/Views/Configure.cshtml",model);
}
[HttpPost]
public async Task Configure(SettingsModel model)
{
_myPluginSettings.UseSandbox = model.UseSandbox;
_myPluginSettings.ApiKey = model.ApiKey;
await _settingService.SaveSetting(_myPluginSettings);
Success("Success");
return Configure();
}
}
So,
your controller inherits from BasePluginController, this adds additional functionality
for the controller like Notification, you can notice invoke Success method in Post request, which
displays success notification in the admin area.
When the controller has the AuthorizeAdmin attribute, it means that we can send a request to the controller if we use an account that has access to the admin area.
Area
attribute works as a prefix for URL.
Default url template is {area}/{controllerName}/{methodName}, so in our case we have: /Admin/MyPlugin/Configure
For
creating settings for our plugin we can simply create a class that implements
marker interface ISettings. Settings are persistent and not required to register
in dependency container (it’s automatic).
In Post
request, we use ISettingService for save/update settings.
public class MyPluginSettings : ISettings
{
public string ApiKey { get; set; }
public bool UseSandbox { get; set; }
}
public class SettingsModel
{
public string ApiKey { get; set; }
public bool UseSandbox { get; set; }
}
Lastly we
create view called Configure.cshtml :
@{ Layout = "_ConfigurePlugin"; }
@model SettingsModel
@using Misc.MyPlugin
@*< - form asp-area="Admin" asp-controller="MyPlugin" asp-action="Configure" method="post" - >*@
< - /form - >
Finally after build ,we have a simple form that save our settings :
You can also
notice how work notification.