Skip to content

Controllers model binding

Alexanderius edited this page Jun 6, 2024 · 6 revisions

Controllers model binding

View model is an object parsed from the request body (for example, JSON string) or the query string.

  • View model can be accessed via controller T Model property;
  • To access view model asynchronously, first, you should call ReadModelAsync method, otherwise model wil be accessed synchronously on first T Model access.
  • View model will be parsed from request only on first ReadModelAsync call or on T Model first access.

To do work with the view models, you should use Controller2<T>, Controller<T> or AsyncController<T> base classes for your controller, and then specify a model type in the type parameter T.

Example

View model class

public class LoginViewModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }

    public bool RememberMe { get; set; }
}

Controller

public class LoginController : AsyncController<LoginViewModel>
{
    public override async Task<ControllerResponse> Invoke()
    {
        await ReadModelAsync();

     // Accessing serialized model
        if (Model.Password == ... && Model.UserName == ...)
        {
            ...
        }

        ...
    }
}

Form

<form method="post">
    <input type="text" name="UserName" />
    <input type="Password" name="Password" />
    <input type="checkbox" name="RememberMe"/> Remember me
    <button type="submit">Login</button>
</form>

Note, that the model serialization and validation will be executed only on ReadModelAsync first call or Model property first access.

By default view model will be serialized from the HTTP GET query string or the HTTP POST form data (depending on current request method). For a JSON type of data you can use JSON serializer.

Properties types

Supported view model properties types by default: string, bool, bool?, int, int?, decimal, decimal?, DateTime, DateTime?, long, long?.

For DateTime serialization you can use DateTimeFormat attribute. By this attribute you can specify the DateTime source data format, for example: [DateTimeFormat("dd.MM.yyyy Hh:mm")]

Properties validation

All validation attributes can be found in Simplify.Web.ModelBinding.Attributes namespace;

Available properties validation attributes by default:

  • [Required] - indicates what field is a required field (can be set for any supported field types);
  • [MaxLength(5)] - specifies string property maximum length;
  • [MinLength(2)] - specifies string property minimum length;
  • [EMailAttribute(2)] - string property should be a valid e-mail address;
  • [Regex(^[a-zA-Z]+$)] - string property should match specified regular expression;
  • [Max(5)] - specifies numerical property maximum value;
  • [Min(5)] - specifies numerical property minimum value;
  • [Range(1, 5)] - specifies numerical property rangle of allowed values;

Custom validation attributes error message

All validation attributes specified above supports custom error message, both directly from string table or just by specifying some string.

When specifying custom error message, by default it will try to load string from StringTable, by it is label ID, for example:

The model

public class LoginViewModel
{
    [Required("NotifyUserNameIsRequired")]
    public string UserName { get; set; }
}

The default StringTable.en.xml from App_Data

<?xml version="1.0" encoding="utf-8" ?>

<items>
    <item name="NotifyUserNameIsRequired" value="User name is required" />
</items>

If you want to specify error message without StringTable you should set second attribute parameter isMessageFromStringTable to false, for example:

public class LoginViewModel
{
    [Required("User name is required", false)]
    public string UserName { get; set; }
}

Custom validation attributes

You can create your custom validation attribute by inheriting from Simplify.Web.Model.Validation.Attributes.ValidationAttribute

For validation, in overloaded Validate method you show throw exception in case of object value parameter is invalid.

Full example

<< Previous page Next page >>

Clone this wiki locally