### Install Simplify.Web Templates
Source: https://github.com/simplifynet/simplify.web/wiki/Getting-started
Installs the Simplify.Web project templates package from nuget.org. This command-line instruction is essential for creating new Simplify.Web projects.
```console
dotnet new -i Simplify.Web.Templates
```
--------------------------------
### Create Simplify.Web Project
Source: https://github.com/simplifynet/simplify.web/wiki/Getting-started
Creates a new Simplify.Web project using a specified template short name and project name. This command utilizes the installed templates to scaffold a new application.
```console
dotnet new sweb.angular -n HelloWorldApplication
```
--------------------------------
### Angular CLI: Serve Application
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Starts the development server for the Angular application. It automatically rebuilds and reloads the application upon source file changes. Access the application via https://localhost:10900/. Requires Angular CLI to be installed.
```bash
ng serve
```
--------------------------------
### Outgoing JSON Controller Example (C#)
Source: https://github.com/simplifynet/simplify.web/blob/master/README.md
An example of a Simplify.Web controller that returns JSON data. It uses the `[Get]` attribute to define the route and returns an array of strings as a JSON response. Includes basic error handling.
```csharp
[Get("api/v1/weatherTypes")]
public class SampleDataController : Controller2
{
private static readonly string[] Summaries =
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public ControllerResponse Invoke()
{
try
{
return Json(Summaries);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(500);
}
}
}
```
--------------------------------
### Static Page Controller Example in C#
Source: https://github.com/simplifynet/simplify.web/blob/master/README.md
This C# code defines a controller that handles HTTP GET requests for a specific route (e.g., '/about'). It's designed to serve static content, rendering a template and adding page title information. Dependencies include the Simplify.Web framework.
```csharp
// Controller will be executed only on HTTP GET request like http://mysite.com/about
[Get("about")]
public class AboutController : Controller
{
public override ControllerResponse Invoke()
{
// About.tpl content will be inserted into {MainContent} in Master.tpl
return StaticTpl("Static/About", StringTable.PageTitleAbout);
}
}
```
--------------------------------
### Angular CLI: Get Help
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Displays help information for the Angular CLI, including an overview and command reference. This is useful for understanding available commands and their options.
```bash
ng help
```
--------------------------------
### String Table XML File Example
Source: https://github.com/simplifynet/simplify.web/wiki/String-table
An example of a string table file in XML format. This file contains key-value pairs for localizable strings, with 'name' as the key and 'value' as the string content. These files should be placed in the App_Data directory.
```xml
```
--------------------------------
### Ingoing JSON Controller Example with Model Validation (C#)
Source: https://github.com/simplifynet/simplify.web/blob/master/README.md
An example of a Simplify.Web controller that accepts JSON data in the request body. It uses `Controller2` to deserialize the incoming JSON into a specified model (`SampleModel`). Includes model validation and specific exception handling for JSON parsing and model validation errors.
```csharp
[Post("api/v1/sendMessage")]
public class SampleDataController : Controller2
{
public ControllerResponse Invoke()
{
try
{
Trace.WriteLine($"Object with message received: {Model.Message}");
return NoContent();
}
catch (Exception e) when (e is ModelValidationException || e is Newtonsoft.Json.JsonException)
{
return StatusCode(400, e.Message);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(500, "Site error!");
}
}
}
public class SampleModel
{
[Required]
public string Message { get; set; }
}
```
--------------------------------
### Create a Simple View in C#
Source: https://github.com/simplifynet/simplify.web/wiki/Views-basics
Demonstrates how to create a custom view by inheriting from the `View` class and implementing the `Get` method to return an `ITemplate`. This is the basic structure for generating HTML content in Simplify.Web.
```csharp
public class LoggedUserPanelView : View
{
public async Task Get(string userName)
{
var tpl = await TemplateFactory.Load("Shared/LoginPanel/LoggedUserPanel");
tpl.Add("UserName", userName);
return tpl;
}
}
```
--------------------------------
### Load About Template with GET Attribute - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
This C# controller loads an 'About.tpl' template file for HTTP GET requests on the '/about' path. It uses the [Get("about")] attribute to define the route and StaticTpl for rendering.
```csharp
[Get("about")]
public class AboutController : Controller
{
public override ControllerResponse Invoke() =>
StaticTpl("Static/About");
}
```
--------------------------------
### V2 Controller: Load and Render Navbar Template
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
Example of a V2 controller that loads a `Navbar.tpl` template file and injects its content into the `DataCollector`'s `Navbar` variable. It uses the `InlineTpl` method for template rendering. This controller is synchronous and returns a `ControllerResponse`.
```csharp
public class NavbarController : Controller2
{
public ControllerResponse Invoke() =>
InlineTpl("Navbar", TemplateFactory.Load("Navbar"));
}
```
--------------------------------
### Angular CLI: Run End-to-End Tests
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Executes end-to-end tests for the Angular application. Requires a package implementing end-to-end testing capabilities to be installed. This command validates the complete application flow.
```bash
ng e2e
```
--------------------------------
### Display Loaded Template Content and Title - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Loads template content using TemplateFactory, gets its string representation, and places it into 'MainContent' along with a specified title in 'Title'.
```csharp
public override ControllerResponse Invoke()
{
return Tpl(TemplateFactory.Load("MyPageTemplate").Get(), StringTable.MyPageTitle);
}
```
--------------------------------
### Access Other Views from a View in C#
Source: https://github.com/simplifynet/simplify.web/wiki/Views-basics
Illustrates how to call other views from within a current view using the `GetView()` method. This allows for modularity and composition of view components. The example shows accessing a `SomePanel` view.
```csharp
public class LoggedUserPanelView : View
{
public async Task Get(string userName)
{
var tpl = await TemplateFactory.Load("Shared/LoginPanel/LoggedUserPanel");
tpl.Add("SomePanel", GetView().Get());
return tpl;
}
}
```
--------------------------------
### HTML Form for View Model Binding
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-model-binding
An example HTML form structured to submit data that can be bound to a view model. Input names correspond to property names in the view model.
```html
```
--------------------------------
### Implement IModelBinder Interface
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-view-model-binders
Provides an example implementation of the IModelBinder interface for a custom model binder. It includes logic to check request content type and deserialize the model, setting it for controller usage.
```csharp
public class MyModelBinder : IModelBinder
{
public Task BindAsync(ModelBinderEventArgs args)
{
// Checking binder applicability
if (args.Context.Request.ContentType == null || !args.Context.Request.ContentType.Contains("required mime type"))
return Task.CompletedTask;
// Deserialization logic
args.SetModel(/* set deserialized model here to use by controllers */);
return Task.CompletedTask;
}
}
```
--------------------------------
### View Component Example in C#
Source: https://github.com/simplifynet/simplify.web/blob/master/README.md
This C# code defines a reusable view component, `LoggedUserPanelView`, which asynchronously loads a template and populates it with a user's name. This component can be integrated into controllers to render dynamic user-specific content. It depends on Simplify.Web's template factory and view system.
```csharp
public class LoggedUserPanelView : View
{
public async Task Get(string userName)
{
// Loading template from LoggedUserPanel.tpl asynchronously
var tpl = await TemplateFactory.LoadAsync("Shared/LoginPanel/LoggedUserPanel");
// Setting userName into {UserName} variable in LoggedUserPanel.tpl
tpl.Add("UserName", userName);
return tpl;
}
}
```
--------------------------------
### Dynamic Controller with High Priority in C#
Source: https://github.com/simplifynet/simplify.web/blob/master/README.md
This C# example demonstrates a controller with a high execution priority (lower value means higher priority). It runs on any request before other controllers and conditionally adds a login panel to pages based on user authentication status. It utilizes asynchronous operations and template rendering.
```csharp
// Controller will be executed on any request and will be launched before other controllers (because they have Priority = 0 by default)
[Priority(-1)]
public class LoginPanelController : AsyncController
{
public override async Task Invoke()
{
return Context.Context.Authentication.User == null
// Data from GuestPanel.tpl will be inserted into {LoginPanel} in Master.tpl
? new InlineTpl("LoginPanel", await TemplateFactory.LoadAsync("Shared/LoginPanel/GuestPanel"))
// Data from LoggedUserPanelView will be inserted into {LoginPanel} in Master.tpl
: new InlineTpl("LoginPanel", await GetView().Get(Context.Context.Authentication.User.Identity.Name));
}
}
```
--------------------------------
### Mock Default Controller with Moq in C#
Source: https://github.com/simplifynet/simplify.web/wiki/Mocking-controllers-and-views
Demonstrates mocking a default controller and asserting its behavior. This example uses the Moq framework to mock the `DefaultController` and verifies that its `Invoke` method returns a `StaticTpl` with the expected template file name. It requires the Moq library for mocking and NUnit for testing.
```csharp
public class DefaultController : Controller
{
public override ControllerResponse Invoke()
{
return new StaticTpl("Default");
}
}
```
```csharp
[TestFixture]
public class DefaultPageControllerTests
{
[Test]
public void Invoke_Default_MainContentSet()
{
// Arrange
var c = new Mock { CallBase = true };
// Act
var result = c.Object.Invoke();
// Assert
Assert.AreEqual("Default", ((StaticTpl)result).TemplateFileName);
}
}
```
--------------------------------
### V2 Controller: Delete User via Service
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
Example of a V2 controller that deletes a user using an injected `IUsersService`. It demonstrates asynchronous operation using `async Task` and returns a `ControllerResponse` with a 204 status code upon successful deletion. This controller leverages dependency injection.
```csharp
[Delete("api/v1/users/{id}")]
public class SampleDataController(IUsersService service) : Controller2
{
public async Task Invoke(int id)
{
await service.DeleteAsync(id);
return StatusCode(204);
}
}
```
--------------------------------
### Implement IModelValidator Interface - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-view-model-validators
Provides an example of implementing the IModelValidator interface for a custom model validator. The Validate method contains the core validation logic.
```csharp
public class MyModelValidator : IModelValidator
{
public void Validate(T model)
{
// Validation logic
}
}
```
--------------------------------
### HTML Select Element Template
Source: https://github.com/simplifynet/simplify.web/wiki/Lists-generator
An example HTML template demonstrating how to use a generated list (e.g., monthsList) within a select element. The placeholder {Items} is where the generated option elements will be inserted.
```html
```
--------------------------------
### Basic Controller Routing with Multiple HTTP Methods (C#)
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-routing
Defines a controller that handles both HTTP GET and POST requests for the '/foo' path. The controller processes requests if the path matches and the HTTP method is supported, otherwise, a 404 error is returned.
```csharp
// Controller will process both HTTP GET and POST requests with "/foo" path
[Get("foo")]
[Post("foo")]
public class FooController : Controller
{
public override ControllerResponse Invoke()
{
return StaticTpl("Foo");
}
}
```
--------------------------------
### Custom Validation Attribute Example (C#)
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-model-binding
Illustrates the structure for creating a custom validation attribute by inheriting from ValidationAttribute and overriding the Validate method in C#.
```csharp
public class CustomValidationAttribute : ValidationAttribute
{
public override void Validate(object value)
{
// Throw an exception if the value is invalid
}
}
```
--------------------------------
### V2 Controller: Serialize Collection to JSON
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
Example of a V2 controller that serializes a collection to a JSON string, bypassing backend page generation. It handles potential exceptions by returning a 500 status code. This controller uses the `Controller2` base class and returns a `ControllerResponse`.
```csharp
[Get("api/weatherTypes")]
public class SampleDataController : Controller2
{
private static readonly string[] Summaries =
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public ControllerResponse Invoke()
{
try
{
return Json(items);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(500);
}
}
}
```
--------------------------------
### V1 Controller: Serialize Collection to JSON
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
Example of a V1 controller that serializes a collection to a JSON string, skipping backend page generation. It includes error handling for exceptions, returning a 500 status code. This controller inherits from the `Controller` base class and overrides the `Invoke` method.
```csharp
[Get("api/weatherTypes")]
public class SampleDataController : Controller
{
private static readonly string[] Summaries =
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public override ControllerResponse Invoke()
{
try
{
return Json(items);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(500);
}
}
}
```
--------------------------------
### Angular CLI: Build Project
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Builds the Angular project for production deployment. The compiled artifacts are placed in the 'dist/' directory. This command is essential for preparing the application for release. Requires Angular CLI.
```bash
ng build
```
--------------------------------
### Configure Simplify.Web with appsettings.json
Source: https://github.com/simplifynet/simplify.web/wiki/Simplify.Web-configuration
This JSON snippet demonstrates how to configure Simplify.Web by defining the `SimplifyWebSettings` section in your `appsettings.json` file. It includes various options to customize the framework's behavior, such as language settings, template paths, caching, and error handling.
```json
{
"SimplifyWebSettings": {
"DefaultLanguage": "en",
"AcceptCookieLanguage": true,
"AcceptHeaderLanguage": true,
"DefaultTemplatesPath": "MyTemplates/Templates",
"LoadTemplatesFromAssembly": true,
"DefaultMasterTemplateFileName": "Master.tpl",
"DefaultMainContentVariableName": "MainContent",
"DefaultTitleVariableName": "Title",
"DefaultStyle": "Main",
"DataPath": "App_Data",
"StaticFilesEnabled": true,
"StaticFilesPaths": "content, scripts, images",
"StringTableFiles": "Titles.xml, Messages.xml",
"DisableAutomaticSiteTitleSet": true,
"HideExceptionDetails": true,
"ErrorPageDarkStyle": true,
"TemplatesMemoryCache": true,
"StringTableMemoryCache": true,
"StaticFilesMemoryCache": true,
"DisableFileReaderCache": true,
"MeasurementsEnabled": true,
"ConsoleTracing": true
}
}
```
--------------------------------
### Angular CLI: Run Unit Tests
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Executes unit tests for the Angular application using Karma. This command ensures the individual components and logic of the application function as expected. Requires Angular CLI and Karma.
```bash
ng test
```
--------------------------------
### Register Custom Model Binder in Startup
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-view-model-binders
Shows how to register a custom model binder, MyModelBinder, within the application's startup configuration. It also demonstrates registering the binder in the IOC container for dependency injection.
```csharp
public class Startup
{
public void Configuration(IAppBuilder app)
{
...
HttpModelHandler.RegisterModelBinder();
app.UseSimplifyWeb();
}
public void ConfigureServices(IServiceCollection services)
{
...
DIContainer.Current.Register(LifetimeType.Singleton);
...
}
}
```
--------------------------------
### Async Controller with Task Response - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
This C# controller demonstrates asynchronous operations by returning a Task. It uses await TemplateFactory.LoadAsync for asynchronous template loading.
```csharp
public class NavbarController : AsyncController
{
public async override Task Invoke() =>
InlineTpl("Navbar", await TemplateFactory.LoadAsync("Navbar"));
}
```
--------------------------------
### Angular CLI: Generate Component
Source: https://github.com/simplifynet/simplify.web/blob/master/src/SampleApps/SampleApp.Angular/ClientApp/README.md
Generates new Angular components, directives, pipes, services, classes, guards, interfaces, enums, or modules. This command streamlines the creation of project files. Requires Angular CLI.
```bash
ng generate component component-name
```
```bash
ng generate directive|pipe|service|class|guard|interface|enum|module
```
--------------------------------
### Simplify.Web Request Pipeline Steps
Source: https://github.com/simplifynet/simplify.web/wiki/Main-Simplify.Web-principles
The Simplify.Web request pipeline outlines the sequence of operations performed when an HTTP request is received. This includes dependency injection, controller execution, response processing, and page generation using templates. Specific steps can be bypassed based on the response type or if static files are being served.
```plaintext
1. Simplify.Web receives an incoming HTTP request
2. Creates instances of controllers via the Simplify.DI IOC container
3. Executes controller instances
4. Processes controller responses
5. Builds page (loads Master.tpl, inserts DataCollector data, sets Simplify.Web variables)
6. Sends the generated page to the client
```
--------------------------------
### C# Custom Bootstrapper Registration for Page Generator
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-Simplify.Web-bootstrapper
Illustrates how to create a custom bootstrapper class `MyBootstrapper` that extends `BaseBootstrapper`. This class registers both the default `PageGenerator` and a custom `IPageGenerator` implementation (`MyPageGenerator`), allowing the framework to automatically load and use the custom implementation.
```csharp
public class MyBootstrapper : BaseBootstrapper
{
public override void RegisterPageGenerator()
{
BootstrapperFactory.ContainerProvider.Register();
BootstrapperFactory.ContainerProvider.Register(r => new MyPageGenerator(r.Resolve()));
}
}
```
--------------------------------
### Registering Simplify.Web Components in IOC Container
Source: https://github.com/simplifynet/simplify.web/wiki/Dependency-injection
This code snippet demonstrates how to automatically register Simplify.Web controllers and views into the IOC container. This is achieved by passing 'true' to the UseSimplifyWeb or UseSimplifyWebNonTerminal methods. Ensure that any constructor-injected dependencies are registered prior to this or before calling the IOC container's Verify method.
```csharp
app.UseSimplifyWeb(true);
// or
app.UseSimplifyWebNonTerminal(true);
```
```csharp
var registrar = ...; // IDIRegistrator instance
registrar.RegisterSimplifyWeb();
```
--------------------------------
### Redirect to URL - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Initiates an HTTP redirect to a specified URL, directing the client's browser to a new web address.
```csharp
public override ControllerResponse Invoke()
{
return Redirect("http://somelink.com");
}
```
--------------------------------
### Load HTML Template Synchronously - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Template-factory
Demonstrates how to synchronously load an HTML template using the Load method of the TemplateFactory class. This method takes the template name as a string argument and returns the loaded template content. Ensure the template exists in the configured templates folder or assembly.
```csharp
var templateContent = TemplateFactory.Load("template name");
```
--------------------------------
### Accessing Web Context Properties
Source: https://github.com/simplifynet/simplify.web/wiki/Web-context
Demonstrates how to access various properties of the WebContext class to retrieve information about the current HTTP request. This includes route, site URL, virtual path, and request/response objects. It's important to call ReadFormAsync and ReadRequestBodyAsync before accessing Form and RequestBody respectively.
```csharp
using Simplify.Web.Context;
// Assuming 'webContext' is an instance of WebContext
string route = webContext.Route;
string siteUrl = webContext.SiteUrl;
string virtualPath = webContext.VirtualPath;
var httpContext = webContext.Context;
var httpRequest = webContext.Request;
var httpResponse = webContext.Response;
// To access form data, ensure ReadFormAsync is called first
await webContext.ReadFormAsync();
IFormCollection formData = webContext.Form;
// To access request body, ensure ReadRequestBodyAsync is called first
await webContext.ReadRequestBodyAsync();
string requestBody = webContext.RequestBody;
bool isAjax = webContext.IsAjax;
bool isAuthenticated = webContext.IsAuthenticated;
// Query parameters are directly accessible via IQueryCollection
IQueryCollection queryParams = webContext.Query;
```
--------------------------------
### Implement Controller with View Model (C#)
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-model-binding
Shows a C# controller inheriting from AsyncController to handle a specific view model. It demonstrates asynchronous model reading and accessing the bound model.
```csharp
public class LoginController : AsyncController
{
public override async Task Invoke()
{
await ReadModelAsync();
// Accessing serialized model
if (Model.Password == ... && Model.UserName == ...)
{
...
}
...
}
}
```
--------------------------------
### Accessing View in Controller - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
This C# controller shows how to access a view component, specifically 'LoginView', using the GetView() method within the controller's Invoke method.
```csharp
public class MyController : Controller
{
public override ControllerResponse Invoke()
{
var view = GetView();
...
}
}
```
--------------------------------
### C# Overriding Internal Type Registrations with RegisterSimplifyWeb
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-Simplify.Web-bootstrapper
Demonstrates an alternative method for overriding internal type registrations using the `RegisterSimplifyWeb` extension method with the `registrationsOverride` parameter. This allows for a more concise way to specify custom registrations for components like the page generator.
```csharp
.RegisterSimplifyWeb(registrationsOverride: x =>
{
x.OverridePageGenerator(r =>
{
r.Register();
r.Register(r => new MyPageGenerator(r.Resolve()));
});
})
```
--------------------------------
### Dynamic Route Parameters in v2 Controllers (C#)
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-routing
Illustrates defining routes with dynamic parts in v2 controllers. Route parameters are accessed directly as method parameters, with their types inferred or explicitly defined. Type mismatches result in a 404 error.
```csharp
[Get("/some-request/{foo}/{bar}/{test}")]
public class ExampleController : Controller2
{
public void Invoke(string foo, bool bar, int test)
{
...
}
}
```
--------------------------------
### Redirector: Redirect to a specified URL
Source: https://github.com/simplifynet/simplify.web/wiki/Redirector
This snippet demonstrates how to use the Redirector class to redirect the client to a specific URL using the RedirectUrl redirection type. It takes the redirection type and the target URL as arguments.
```csharp
Redirector.Redirect(RedirectionType.RedirectUrl, "http://someurl");
```
--------------------------------
### Controller Base Classes for MVVM in Simplify.Web
Source: https://github.com/simplifynet/simplify.web/wiki/Main-Simplify.Web-principles
Simplify.Web provides base controller classes to facilitate the MVVM pattern by allowing controllers to create view models from HTTP requests. These classes are essential for managing data binding and serialization within the framework. Dependencies include the Simplify.Web framework itself.
```csharp
public class Controller : ControllerBase where T : class, new()
public class Controller2 : Controller where T : class, new()
public class AsyncController : ControllerBase where T : class, new()
```
--------------------------------
### C# Custom Page Generator Implementation
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-Simplify.Web-bootstrapper
Defines a custom page generator class `MyPageGenerator` that decorates the existing `IPageGenerator`. It takes the base generator as a dependency and allows for custom logic within the `Generate` method. This is a prerequisite for overriding the default page generation behavior.
```csharp
public class MyPageGenerator(IPageGenerator baseGenerator) : IPageGenerator
{
public string Generate(IDataCollector dataCollector)
{
var result = baseGenerator.Generate(dataCollector);
// Your custom code
return result;
}
}
```
--------------------------------
### Load Navbar Template in Controller - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-basics
This C# controller loads a 'Navbar.tpl' template file and assigns it to the 'Navbar' variable in the DataCollector. It utilizes the InlineTpl method for template rendering.
```csharp
public class NavbarController : Controller
{
public override ControllerResponse Invoke() =>
InlineTpl("Navbar", TemplateFactory.Load("Navbar"));
}
```
--------------------------------
### Display Text and Title - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Places a given string into the 'MainContent' variable and a specified title into the 'Title' variable of the DataCollector.
```csharp
public override ControllerResponse Invoke()
{
return Tpl("Some text", StringTable.MyPageTitle);
}
```
--------------------------------
### Load Static Template with Title - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Loads a specified template and adds a site title to the 'Title' variable of the DataCollector, in addition to loading the template data into 'MainContent'.
```csharp
public override ControllerResponse Invoke()
{
return StaticTpl("MyPageTemplate", StringTable.MyPageTitle);
}
```
--------------------------------
### Load HTML Template Asynchronously - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Template-factory
Illustrates how to asynchronously load an HTML template using the LoadAsync method of the TemplateFactory class. This method is suitable for scenarios where blocking the main thread is undesirable. It returns a Task that resolves to the template content.
```csharp
var templateContent = await TemplateFactory.LoadAsync("template name");
```
--------------------------------
### Clear Default Binders and Register Custom Binder
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-view-model-binders
Demonstrates how to clear all default model binders and then register a specific custom binder, MyModelBinder. This approach ensures only the custom binder is used.
```csharp
HttpModelHandler.ModelBindersTypes.Clear();
HttpModelHandler.RegisterModelBinder();
```
--------------------------------
### Load Text Document with FileReader in C#
Source: https://github.com/simplifynet/simplify.web/wiki/File-reader
Illustrates loading a text file (e.g., HTML) using FileReader.LoadTextDocument. Similar to XML loading, it respects language prefixes and falls back to the default language if the specific file is not found.
```csharp
public class MyController : Controller
{
public override ControllerResponse Invoke()
{
// Loads SomeFile.html
var myData = FileReader.LoadTextDocument("SomeFile.html");
...
}
}
```
--------------------------------
### Load XML Document with FileReader in C#
Source: https://github.com/simplifynet/simplify.web/wiki/File-reader
Demonstrates loading an XML document using FileReader.LoadXDocument. The file is expected to be in the data folder with a language prefix (e.g., Menu.en.xml). If the current language file is not found, the default language file is used. The file extension can be omitted.
```csharp
public class MyController : Controller
{
public override ControllerResponse Invoke()
{
// Loads Menu.en.xml file
var myData = FileReader.LoadXDocument("Menu.xml");
...
}
}
```
```csharp
public class MyController : Controller
{
public override ControllerResponse Invoke()
{
// Loads Menu.en.xml file
var myData = FileReader.LoadXDocument("Menu");
...
}
}
```
--------------------------------
### Response Types in Simplify.Web
Source: https://github.com/simplifynet/simplify.web/wiki/Main-Simplify.Web-principles
Simplify.Web supports various response types that controllers can return to handle different scenarios. These include redirecting the client, returning plain content, JSON data, or a specific status code. The choice of response type can affect the subsequent processing steps in the Simplify.Web pipeline.
```csharp
Redirect
Content
Json
StatusCode
```
--------------------------------
### Dynamic Route Parameters in v1 Controllers (C#)
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-routing
Demonstrates how to define a route with a dynamic part in v1 controllers. The dynamic part '{userName}' is captured and can be accessed via the RouteParameters property. If the URL does not match the defined pattern, a 404 error is returned.
```csharp
[Get("/user/show/{userName}")]
public class EditUserController : Controller
{
public override ControllerResponse Invoke()
{
// Getting parsed user name
var currentUserName = RouteParameters.userName;
...
}
}
```
--------------------------------
### Enable File Caching with FileReader in C#
Source: https://github.com/simplifynet/simplify.web/wiki/File-reader
Shows how to enable in-memory caching for files loaded via FileReader.LoadTextDocument and FileReader.LoadXDocument by passing 'true' as the second parameter. File caching can be globally disabled through Simplify.Web configuration.
```csharp
...
FileReader.LoadTextDocument("SomeFile.html", true);
FileReader.LoadXDocument("Menu", true);
...
```
--------------------------------
### Load Static Template - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Loads a specified template and places it into the data collector. The template data is added to the 'MainContent' variable of the DataCollector. This version only loads the template data.
```csharp
public override ControllerResponse Invoke()
{
return StaticTpl("Default");
}
```
--------------------------------
### Send File Response - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Sends a file to the client with specified filename, content type, and byte content. The HTML page will not be generated.
```csharp
public override ControllerResponse Invoke()
{
return new File("MyFile.txt", "text/plain", Encoding.UTF8.GetBytes("My file content"));
}
```
--------------------------------
### Setting Language via Cookie - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Language-manager
Demonstrates how to set the language for the current request and create a persistent language cookie using the SetCookieLanguage method of the LanguageManager class. This method ensures the language preference is maintained across subsequent requests.
```csharp
LanguageManager.SetCookieLanguage("en");
```
--------------------------------
### Register Custom Model Validator - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Custom-view-model-validators
Demonstrates how to register a custom model validator using HttpModelHandler.RegisterModelValidator. It also shows how to register the validator with the DI container as a singleton.
```csharp
HttpModelHandler.RegisterModelValidator();
DIContainer.Current.Register(LifetimeType.Singleton);
```
--------------------------------
### Redirect using RedirectionType - C#
Source: https://github.com/simplifynet/simplify.web/wiki/Controller-responses
Performs a redirect based on a predefined RedirectionType, such as redirecting to the previous page.
```csharp
public override ControllerResponse Invoke()
{
return Redirect(RedirectionType.PreviousPage);
}
```
--------------------------------
### Generate Months List in C#
Source: https://github.com/simplifynet/simplify.web/wiki/Lists-generator
Demonstrates how to use the ListsGenerator class in a C# controller to generate an HTML option list for months. This list can then be used to populate select elements in a template.
```csharp
public class MyController : Controller
{
public override ControllerResponse Invoke()
{
// This call will generate an HTML "