Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Controllers model binding

Alexanderius edited this page Jun 25, 2019 · 3 revisions

Controllers model binding

View model can be serialized from a HTTP GET request query string or a POST data and then used in the controller. To do this, you should use Controller<T> or AsyncController<T> base classes for your controller, and then specify a model type in 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 : Controller<LoginViewModel>
{
    public override ControllerResponse Invoke()
    {
        // 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, what model serialization and validation will be executed only on the 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;

Full example

<< Previous page Next page >>

Clone this wiki locally