Oct 4 2017

Building Web applications with Knockout.js and ASP.NET core

Category: Asp.net | Asp.net core | MVC | TypeScript | WebApi | JavaScriptFrancesco @ 05:40

Amongst all the client side frameworks backed by big companies, React.js and Angular.js appear to be the most popular. However, Knockout.js still maintains a good market share, thanks to its interesting peculiarities.

Knockout is based on an MVVM paradigm similar to Angular.js, but unlike React.js. While it is adequate for modular complex applications, at the same time, it is very simple to mix with server side templating, similar to React.js, but unlike Angular.js….Read full article

Contact us if you want to learn more

aspnet-core-running-spa

Tags: , ,

May 9 2017

Customization And Localization Of ASP.NET Core MVC Default Validation Error Messages

Category: MVC | Asp.net core | Asp.netFrancesco @ 00:25

This time my post has been published on the MSDN Blog! Enjoy it!.

………Moreover, the new validation provider architecture made it easy to override the default messages built-in, in the .Net validation attributes with customized default messages defined in resource files. This way, the user can provide global custom messages once and for all, thus avoiding the burden of having to specify an error message in each occurrence, of each attribute.This article goes into detail about how to customize both all ASP.NET MVC specific error messages, and all default messages coming from validation attributes……Read full article

Tags: , , , , ,

May 7 2017

Asp.net core: Deserializing Json with Dependency Injection

Category: MVC | Asp.net core | Asp.netFrancesco @ 21:30

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

In a previous post I discussed how to model bind Interfaces/abstract classes with the help of Asp.net core dependency injection features. However, the technique discussed there doesn’t apply to Json data added to the request body, since request body is processed by the BodyModelBinder that, in turn, selects a formatter based on the request content-type header. The formatter for “application/json” is a wrapper for Json.net, so the code of our previous “interfaces model binder” is never called, and also if called it wouldn’t be able to process Json data in the request body.

The behavior of Json.net serializer/deserializer may be customized through an MvcJsonOptions options object.In this post I am going to show how to modify Json.net behavior so that it attempts to use Dependency Injection to create any .Net object before creating it through its constructor. This, will enable not only the deserialization of interfaces, but also the customization of object creation through Asp.net Core DI engine.

Preparing the project

As a first step let create a new asp.net core project named “JsonDI”:

Project

Select “no authentication” to simplify the code created by VS project template.

Then let create a new folder called “Models” and add it the following “IPerson.cs” file, that contains both an interface definition and its default implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JsonDI.Models
{
    public interface IPerson
    {
       string Name { get; set; }
       string Surname { get; set; }
    }
    public class DefaultPerson: IPerson
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

Now let modify the code of the Home controller to add an HttpPost for the Index action:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JsonDI.Models;

namespace JsonDI.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Index([FromBody] IPerson model)
        {
            return Json(model);
        }
        ....
        ....

We need an Ajax call to send Json data to our newly created HttpPost action method. Go to the Index.cshtml file in the Views/Home folder and substitute its code with the code below:

@{
    ViewData["Title"] = "Deserialization with DI";
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    
    <button data-url="@Url.Action("Index", "Home")" type="button" class="test btn btn-default">Submit</button>
</form>
@section Scripts
{
    <script type="text/javascript">
        $(".test").click(function (evt) {
            var url = $(evt.target).attr("data-url");
            $.ajax(url,
                {
                type: 'POST',
                data: JSON.stringify({
                    name: "Francesco",
                    surname: "Abbruzzese"
                }),
                success: function () { alert("message received"); },
                contentType: "application/json",
                dataType: 'json'
            });
        });
    </script>
}

Now place a breakpoint here:

Breakpoint

…and run the project.

When we click the “Submit” button an Ajax request is issued to our HomeController that contains an IPerson interface in the request body. However, when the breakpoint is hit, we may verify that the model parameter is null! In fact Json.net is not able to deserialize the IPerson interface because it doesn’t know how to create an instance of it.

Enriching Asp.net Core Dependency Injection.

Pieces of code that need Asp.net Core Dependency Injection engine creates type instances do it through the IServiceProvider interface that contains the unique method “GetService(Type t)”. Accordingly, we may create a type instance calling GetService or some other extension method that, in turn, calls it, but we are not able to ask if a type has been registered with the DI engine. This problem may be solved using a third party DI engine, such as Autofac. In this section we will show how to add this capability without using third party DI engines.

Let add an “Extensions” folder to the project. We will place there all extensions we need to have Json.net use DI. As a first step let define an interface containing all features we need and that are not exposed by IServiceProvider:

using System;

namespace JsonDI.Extensions
{
    public interface IDIMeta
    {
        bool IsRegistred(Type t);
        Type RegistredTypeFor(Type t);
    }
}

I called it IDIMeta because it provides meta-information about the content of the the DI container. The first method returns if a type has been registered with the DI engine, and the second returns the type that will be actually created when requiring an instance of the registered type.

The actual implementation of the above interface uses the IServiceCollection available in the ConfigureServices method of the Startup.cs class to collect all information needed to implement the interface methods in a dictionary :

using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;

namespace JsonDI.Extensions
{
    public class DIMetaDefault: IDIMeta
    {
        IDictionary<Type, Type> register = new Dictionary<Type, Type>();
        public DIMetaDefault(IServiceCollection services)
        {
            foreach (var s in services)
            {
                register[s.ServiceType] = s.ImplementationType;
            }
        }
        public bool IsRegistred(Type t)
        {
            return register.ContainsKey(t);
        }

        public Type RegistredTypeFor(Type t)
        {
            return register[t];
        }
    }
}

As a final step we need to register IDIMeta itself in the DI engine, by adding the code below to the ConfigureServices method of the Startup.cs class:

services.TryAddSingleton<IDIMeta>(s =>
{
    return new DIMetaDefault(services);
});

Later on we will show the whole code to be added to the ConfigureServices method of the Startup.cs class.

Customizing Json.net behavior

Now we are ready to customize Json.net behavior! The way Json.net serializes/deserializes types is specified by ContractResolvers. ContractResolvers return a “contract” for each type that contains all information on how to deal with that type. In particular each contract specifies how to create an instance of the type and how to fill its properties. The way to fill type properties may be customized by passing a custom converter in the “Converter” property of the contract. However, we don’t need custom converters since we must customize just the way types are created.

Our custom ContractResolver inherits form the built-in “CamelCasePropertyNamesContractResolver” that is the one used as a default by Asp.net Core:

using System;
using Newtonsoft.Json.Serialization;

namespace JsonDI.Extensions
{
    public class DIContractResolver: CamelCasePropertyNamesContractResolver
    {
        IDIMeta diMeta;
        IServiceProvider sp;
        public DIContractResolver(IDIMeta diMeta, IServiceProvider sp)
        {
            this.diMeta = diMeta;
            this.sp = sp;
        }
        protected override JsonObjectContract CreateObjectContract(Type objectType)
        {

            if (diMeta.IsRegistred(objectType))
            {
                JsonObjectContract contract = DIResolveContract(objectType);
                contract.DefaultCreator = () => sp.GetService(objectType);

                return contract;
            }

            return base.CreateObjectContract(objectType);
        }
        private JsonObjectContract DIResolveContract(Type objectType)
        {
            var fType = diMeta.RegistredTypeFor(objectType);
            if (fType != null) return base.CreateObjectContract(fType);
            else return CreateObjectContract(objectType);
        }
    }
}

We override the CreateObjectContract method to modify the custom contract. If the type our ContractResolver has been invoked on is registered in the DI container we call DIResolveContract that, if available, returns a contract for the type that will be actually created by the DI engine. If no type is specified DIResolveContract falls back on a contract for the original type (which might have less properties than the actual type created). After that CreateObjectContract changes the contract DefaultCreator property to use DI.

Our ContractResolver needs both IServiceProvider and IDIMeta to do its job, so we passed them in its constructor.

Installing our DIContractResolver

Our DIContractResolver may be installed by configuring the MvcJsonOptions options object. In my previous posts of the custom model binding series I showed how to configure options by passing a lambda function to various extension methods in the ConfigureServices method of the Startup.cs class. We may also factor out the configuration code for each specific option object in a class by writing a class that inherits from IOption<MyOptionObject>:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace JsonDI.Extensions
{
    public class JsonOptionsSetup: IConfigureOptions<MvcJsonOptions>
    {
        IServiceProvider serviceProvider;
        public JsonOptionsSetup(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }
        public void Configure(MvcJsonOptions o)
        {
            o.SerializerSettings.ContractResolver =
                new DIContractResolver(serviceProvider.GetService<IDIMeta>(), serviceProvider);
        }
    }
}

After that, it is enough to call “services.AddTransient<IConfigureOptions<MvcJsonOptions>, JsonOptionsSetup>();” in the ConfigureServices method of the Startup.cs class. Summing up the whole code of the ConfigureServices method of the Startup.cs class is:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            
            services.AddTransient<IPerson, DefaultPerson>();
            services.TryAddSingleton<IDIMeta>(s =>
            {
                return new DIMetaDefault(services);
            });
            services.AddTransient<IConfigureOptions<MvcJsonOptions>, JsonOptionsSetup>();
        }

For the above to compile properly we need the “usings” below:

using JsonDI.Extensions;
using JsonDI.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

 

That’s all! Run the project, click the submit button and wait on our previous breakpoint. This time the IPerson model contains the right data sent by the client!

Stay Tuned!

Francesco

Tags: , , , ,

Apr 5 2017

Model binding interfaces: fixing server side validation

Category: MVC | Asp.net core | Asp.netFrancesco @ 20:55

 

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

This is a follow-up of my previous post on model binding interfaces, so please read it before going on with this post. I suppose also you have available the VS solution built in the previous post.

The problem

We use interfaces when we don’t want dependencies on how a “surface behavior” is implemented. As a matter of fact the same class may implement several interfaces and when we access it through one of these interfaces we want that each effect of the computation depends just on the way the interface is defined and not on the specific class peculiarities. In particular, we want that object validation performed through that interface depends only on the way the interface is defined.

That is why in my previous post I defined all validation attributes in the interface, instead of the interface implementation:

public interface ITestInterface
{
    [Range(1, 10)]
    int TestProperty { get; set; }
}

Unluckily, this doesn’t ensure model binder uses that validation rule. As a matter of fact the model binder has a “strange” behavior, namely if the interface is the root model received by the action method, it uses the validation attributes defined in the class that implements the interface,while if the interface is nested inside the root ViewModel received by the action method it do uses the validation attributes defined on the interface.

The reason of this behavior is quite simple: during validation the type of the root ViewModel is inferred by calling ‘GetType()’ on the model returned by the model binder, while the type of nested objects is inferred by the type of the property they are in.

About client side validation, it always uses the attributes defined in the interface.

 

In my previous post I suggested using the ‘ModelMetadataTypeAttribute’ to force usage of validation attributes defined in the interface:

[ModelMetadataType(typeof(ITestInterface))]
public class TestViewModel : ITestInterface
{
    public int TestProperty { get; set; }
}

Unluckily, this solution suffers of several problems:

  1. All validation attributes defined in the interfaces doesn’t substitute the ones defined in the class but they are simply added to them.
  2. A class may have just a single ‘ModelMetadataTypeAttribute’ so if a class implements several interfaces this technique can’t be used
  3. We cant make the class that implements the interface depends on peculiarities of the presentation layer since this would break separation of concerns between layers, thus adding the ‘ModelMetadataTypeAttribute’  just to solve a technical problem we have in the presentation layer is not a good practice.

Therefore, we are forced to modify the default behavior of the built-in validation system.

The solution

In all previous versions of Asp.net Mvc validation were performed during the model-binding recursive steps. In asp.net core, validation is performed after model binding has returned an objects tree, with a recursive visit of the whole tree. This way, the same validation process may be applied also to models that have been built by formatters (such as, for instance, the Json formatter that processes Json objects). Namely, as soon as model binding returns an objects tree an implementation of the “IObjectModelValidator” interface is retrieved through dependency injection and its “Validate” model is called passing it the model returned by the model binder and other parameters we will analyze later on in this section.

The “IObjectModelValidator” default implementation performs some preparation steps, then calls GetTipe on the model passed to its Validate method to get the root type to validate, and finally it calls a recursive visitor that traverses the whole tree for validation.

We need to substitute the default implementation with an implementation that instead of calling GetType to get the root type uses the type declared in the action method. This way instead of validating the interface implementation we might validate the interface. No modification is needed to the recursive visitor since it doesn’t use GetType but the types declared in the type properties.

Unluckily the “Validate” method is not passed the type declared in the action method but just the overall ActionContext.

The method below is able to extract the type declared in the action method from the model type extracted with GetType, the ActionContext, and initial prefix passed to the validate method. This initial prefix is either the empty string or the name of the parameter of the action method that is being processed (more details on this, later on):

private Type referenceType(string prefix, Type modelType, ActionContext actionContext)
{
    var parameterDescriptors = actionContext.ActionDescriptor.Parameters;
    ParameterDescriptor parameter;
    if (string.IsNullOrWhiteSpace(prefix))
        parameter = parameterDescriptors
            .Where(m => m.ParameterType.GetTypeInfo().IsAssignableFrom(modelType))
            .FirstOrDefault();
    else
    {
        parameter = parameterDescriptors
            .Where(m => m.Name == prefix && m.ParameterType.GetTypeInfo().IsAssignableFrom(modelType))
            .FirstOrDefault();
    }
    if (parameter != null && parameter.ParameterType.GetTypeInfo().IsInterface)
        return parameter.ParameterType;
    else return modelType;
}

We look for the parameter we need the type of in the list of all parameter descriptors.If the initial prefix is the empty string we don’t have the name of the parameter we are looking the type of, so we try to find it through the type of the model (model type must be “assignable” to the parameter type), otherwise we try a match for both name and type.

Finally if the parameter is an interface we use its type otherwise we revert to the default behavior an use the model type obtained with GetType.

The whole code of our custom implementation is :

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System.Linq;
using System.Reflection;

namespace ModelBindingInterfaces.Validation
{
    public class EnhancedObjectValidator: IObjectModelValidator
    {
        private readonly IModelMetadataProvider _modelMetadataProvider;
        private readonly ValidatorCache _validatorCache;
        private readonly IModelValidatorProvider _validatorProvider;


        public EnhancedObjectValidator(
            IModelMetadataProvider modelMetadataProvider,
            IList<IModelValidatorProvider> validatorProviders)
        {
            if (modelMetadataProvider == null)
            {
                throw new ArgumentNullException(nameof(modelMetadataProvider));
            }

            if (validatorProviders == null)
            {
                throw new ArgumentNullException(nameof(validatorProviders));
            }

            _modelMetadataProvider = modelMetadataProvider;
            _validatorCache = new ValidatorCache();

            _validatorProvider = new CompositeModelValidatorProvider(validatorProviders);
        }

        private Type referenceType(string prefix, Type modelType, ActionContext actionContext)
        {
            var parameterDescriptors = actionContext.ActionDescriptor.Parameters;
            ParameterDescriptor parameter;
            if (string.IsNullOrWhiteSpace(prefix))
                parameter = parameterDescriptors
                    .Where(m => m.ParameterType
                        .GetTypeInfo().IsAssignableFrom(modelType))
                    .FirstOrDefault();
            else
            {
                parameter = parameterDescriptors
                    .Where(m => m.Name == prefix && m.ParameterType.GetTypeInfo()
                        .IsAssignableFrom(modelType))
                    .FirstOrDefault();
            }
            if (parameter != null && parameter.ParameterType.GetTypeInfo().IsInterface)
                return parameter.ParameterType;
            else return modelType;
        }
        public void Validate(
            ActionContext actionContext,
            ValidationStateDictionary validationState,
            string prefix,
            object model)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            var visitor = new ValidationVisitor(
                actionContext,
                _validatorProvider,
                _validatorCache,
                _modelMetadataProvider,
                validationState);

            var metadata = model == null ? null :
                _modelMetadataProvider
                    .GetMetadataForType(referenceType(prefix, model.GetType(),
                        actionContext));
            visitor.Validate(metadata, prefix, model);
        }
    }
}

Our custom implementation may be installed easily in the DI section of our project Startup.cs.

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();

            services.AddMvc(o =>
            {
                o.ModelBinderProviders.Insert(0,
                    new ModelBinders.InterfacesModelBinderProvider());
            });
            services.TryAddSingleton<IObjectModelValidator>(s =>
            {
                var options = s.GetRequiredService<IOptions<MvcOptions>>().Value;
                var metadataProvider = s.GetRequiredService<IModelMetadataProvider>();
                return new EnhancedObjectValidator(metadataProvider,
                    options.ModelValidatorProviders);
            });
        }

We use the possibility offered by DI to get an instance through a Lambda, since, in the constructor of our implementation, we need the current model metadata provider that is contained in the MvcOptions object.

Proof of correctness of parameter type extraction algorithm

If you are not interested in the details of why the parameter extraction algorithm I propose always works, that is,why  it never guesses the wrong parameter you may jump this section.

In case the algorithm receives the exact parameter name, no error is possible, but what happens when it receives the empty string? There might be several parameters that are assignable from the model type, how are we sure to select the right one?

The answer is very simple: when when the algorithm receives the empty string there can’t be several parameters compatible with the model type! In fact, we receives the empty string instead of the parameter name when the name of the action method parameter is not used as a prefix in the name of any input field submitted. In fact the model binder always attempts matching field names with and without the parameter names as prefixes. Usually, we don’t add the parameter name prefix to the field names when the action method has an unique parameter, but this is not compulsory.

However, for sure, when we omit parameter names in field names we can’t have several parameters whose types share properties with the same names, otherwise the model binding process would be ambiguous. Therefore, when parameter names do not prefix field names we can’t have several parameters compatible with the same type (otherwise the properties of the model compatible with both parameters would create ambiguities).

Cautions!

Our algorithm guesses the right correctly interface type when the model binding process is invoked directly by the framework during action method parameters instantiation. However, it doesn’t work if you invoke manually model binding by calling helper functions like “TryUpdateModelAsync” from within an action method, so please, in this case do not use interfaces as parameter types.

Moreover, pay attention when using Interfaces! Validation attributes defined on interfaces are not inherited by derived interfaces or classes implementing them, since interfaces are just prescriptions and can’t furnish any “code” to the types that implement them.

 

That’s all for now

Stay tuned!

Francesco

Tags: , ,

Mar 17 2017

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

Category: MVC | Asp.net core | Asp.netFrancesco @ 01:53


Custom Model Binding in Asp.net Core Mvc, 1

Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Model binding interfaces: fixing server side validation

Asp.net core: Deserializing Json with Dependency Injection

 

In this last post of the model binding series I will discuss model binders that are not specific for a single type. That is, model binders able to handle generic types, and/or categories of types. Typical examples of these model binders are the built-in model binders for all complex types, all IEnumerables, and all dictionaries. If we give a look at all these model binders, we see that they recursively call the binding process itself to bind child elements and/or properties. They do this after having created a child binding context with a call to bindingContext.EnterNestedScope that loads the newly created child binding context in the same bindingContext variable. The call is enclosed within an using block, so that the original bindingContext is restored after exiting the block.

As an example we will build a custom model binder for interfaces, that is, a model binder that binds interfaces by looking for a an implementation in the Asp.net core Dependency Injection framework, and then by calling back the binding process itself on that implementation. Interfaces model binding is not only a good example of recursive model binding but also an useful programming tool for the following reasons:

  1. Using interfaces instead of concrete ViewModels allows a better separation between business layer and user interface layer.
  2. ViewModels inheritance allows a better reuse of views and metadata (validation attributes, DisplayAttributes, etc.), and interfaces overcome the limitation of inheriting from a single father class, since each interface may inherit from multiple other interfaces.

Asp.net core Mvc already has a model binder that is able to inject objects from the Dependency Injection engine into action methods. Its usage is triggered by the FromServicesAttribute, and it just injects object instances as they are returned by the DI engine without binding their properties to the input received by the client. Our custom model binder, instead, will be invoked only on interfaces or abstract classes and only when no FromServicesAttribute is provided. Moreover, once invoked it will bind all interface/abstract class properties against the input received by the client.

Preparing the project

As a first step let create a new asp.net core project named “ModelBindingInterfaces” and let select “no authentication”. Then let create a new folder called “ViewModels”.

Now let add an Interface called “ITestInterface”  to this folder :

using System.ComponentModel.DataAnnotations;

namespace ModelBindingInterfaces.ViewModels
{
    public interface ITestInterface
    {
        [Range(1, 10)]
        int TestProperty { get; set; }
    }
}

and a class implementing this interface, called “TestViewModel”:

using Microsoft.AspNetCore.Mvc;

namespace ModelBindingInterfaces.ViewModels
{
    [ModelMetadataType(typeof(ITestInterface))]
    public class TestViewModel : ITestInterface
    {
        public int TestProperty { get; set; }
    }
}

All metadata are added to the interface, so, to be sure they are used also by its implementation, we define the interface as a “ModelMetaDataType” for its implementation.

Now let register the above pair in the dependency injection engine, by adding the last line of the code below to the “startup.cs” file:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();

Finally, we need a controller and a test view. Let modify the “Index” action method of the HomeController in “HomeController.cs” as follows:

public IActionResult Index()
{
    return View();
}
[HttpPost]
public IActionResult Index(ITestInterface model)
{
    return View(model);
}

 

And also its “Views\Home\Index.cshtml” associated view:

@model ModelBindingInterfaces.ViewModels.ITestInterface

@{
    ViewData["Title"] = "Model Binding Interfaces";
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    <div class="form-group">
        <label asp-for="TestProperty" class="control-label"></label>
        <input asp-for="TestProperty" class="form-control">
        <span asp-validation-for="TestProperty" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

 

As you can see both controller and view reference only the interface. The only chunk of code that mentions its actual implementation is the DI container definition.

If you run the project as it is now, and try to submit the Index form, you get the following error:

“ModelBindingInterfaces.ViewModels.ITestInterface' does not have a default constructor”

In fact, all default model binders are not able to create automatically an instance of the  “ITestInterface'” interface.

Implementing the custom model binder

Our model binder should perform a job similar to the one of the built-in ComplexTypeModelBinder. The only difference being that instead of attempting to create an interface it should invoke the the DI engine to get an instance of a class that implements the interface. The code of the ComplexTypeModelBinder is quite complex, but its kernel is the invocation of “bindingContext.EnterNestedScope” on each type property. EnterNestedScope is passed an updated "ModelName" obtained by appending ".<property name>" to the current ModelName. ModelName is used to retrieve data from the input received by the client once a leaf property is reached, as we have seen in the previous post of this series. Inside the using block associated to EnterNestedScope there is a call to the “BindProperty” method, that in turn, retrieves the right binder for the property by looking in the dictionary of all property binders that is passed in the ComplexTypeModelBinder constructor. Once the right binder is found it is invoked on the child binding context created by “bindingContext.EnterNestedScope”. The result is finally stored in a variable defined outside the using block.

All results returned by the recursive calls on all  properties are then used to populate an instance of the type created by the “CreateModel” method.

We need just to modify “CreateModel” so that it uses the DI engine to get an instance of the type. Thus, we may inherit from the ComplexTypeModelBinder  and override its CreateModel method.

Let add the new “ModelBinders” folder to our project, and then add our “InterfacesModelBinder” class to this folder:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace ModelBindingInterfaces.ModelBinders
{
    public class InterfacesModelBinder : ComplexTypeModelBinder
    {

        public InterfacesModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinder)
            : base(propertyBinder)
        {

        }
        protected override object CreateModel(ModelBindingContext bindingContext)
        {
            return bindingContext.HttpContext
                .RequestServices.GetService(bindingContext.ModelType);
        }
    }
}

 

Implementing the provider

In the previous post of the series we have seen that model binders are selected and created by model binder providers, so now it is time to write a provider for our custom model binder. Before start coding we need an answer to two questions:

  1. When the provider must return a not null result, meaning when we are in the right situation when our custom model binder must be used.
  2. Which parameters to pass in the constructor of the model binder.

The right conditions for using our “InterfacesModelBinder” are:

  • we are going to bind either an interface or an abstract class
  • the interface is not an IEnumerable, otherwise the built-in CollectionModelBinder/DictionaryModelBinder would be more appropriate
  • no FromServicesAttribute is in place, since this attribute is used when the user needs just the injection of a type with no subsequent binding of the type against the input provided by the client.

Finally, the constructor of our “InterfacesModelBinder” needs a dictionary whose entries associate the right binder to each type property.

Now we have all information to add our InterfacesModelBinderProvider class to the ModelBinders folder:

using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ModelBindingInterfaces.ModelBinders
{
    public class InterfacesModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!context.Metadata.IsCollectionType &&
                (context.Metadata.ModelType.GetTypeInfo().IsInterface ||
                 context.Metadata.ModelType.GetTypeInfo().IsAbstract)  &&
                (context.BindingInfo.BindingSource == null ||
                !context.BindingInfo.BindingSource
                .CanAcceptDataFrom(BindingSource.Services)))
            {
                var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
                for (var i = 0; i < context.Metadata.Properties.Count; i++)
                {
                    var property = context.Metadata.Properties[i];
                    propertyBinders.Add(property, context.CreateBinder(property));
                }
                return new InterfacesModelBinder(propertyBinders);
            }

            return null;
        }
    }
}

The metadata of each property are taken from the MetaData.Properties array contained in the context object passed to the GetBinder method of the provider. Then, a binder for the property is created by invoking the CreateBinder method of the same context object on the property metadata.The remainder of the code is self-explicative.

The provider is installed with the same procedure of our previous post. Go to the startup.cs file and modify the ConfigureServices method as shown below:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddTransient<ITestInterface, TestViewModel>();
            services.AddMvc(o =>
            {
                o.ModelBinderProviders.Insert(0,
                    new ModelBinders.InterfacesModelBinderProvider());
            });

As in our previous post, our provider is inserted at the top of the list of all providers to avoid that some other built-in provider might return a different model binder also when all conditions for the application of our InterfacesModelBinder are satisfied.

We have Finished! Run the project and verify how the interface is bound properly, and also how validation errors work properly.

Our series on model binding ended

but stay tuned!

We are preparing new enjoying adventures!

Francesco

Tags: , ,

Feb 22 2017

Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Category: MVC | Asp.net core | Asp.netFrancesco @ 05:51


Custom Model Binding in Asp.net Core Mvc, 1

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

The second post of the “Custom Model Binding” series is dedicated to “fixed representation” complex types, that is to types that for some reason cannot be handled as “simple types” but that are rendered with some pre-defined input fields. For a general discussion, on Custom Model Binding, please refer to the first post of the series. As an example of the general technique we will design and install a custom model binder for the DateTimeOffset .Net type. The DateTimeOffset is a generalization of the Datetime that contains also the Time Zone offset associated to the DateTime value. We can’t use the simple technique described in the first post of the series for two reasons:

  1. The DateTimeOffset is a system type so we can’t apply a custom TypeConverterAttribute to its definition.
  2. We need the DateTime and Time Zone offset be rendered into separate fields so that the user may edit date and time with a datetime-local Html5 input type. The Time Zone offset part will be stored in an hidden input field that will be handled automatically by some JavaScript. The hidden field must be updated each time the datetime-local input value changes because the Time Zone Offset is not constant but depends on the selected date (Daylight saving time on/off). On the server side we need a custom model binder that is able to combine both inputs into a DateTimeOffset instance.

More specifically, a DateTimeOffset that is rendered and then posted to the server again passes through the following transformations:

  1. DateTime and Time Zone offset are rendered in the two dedicated input fields described above.
  2. Once on the client side some JavaScript converts the DateTime/Time Zone offset pair into the client time zone, so that user may edit it in a datetime-local input field (we suppose the browser supports datetime-local)
  3. Each time the user changes the datetime value the associated Time Offset field is updated by some JavaScript
  4. Once the form is posted a custom model binder combines both the DateTime and the client Time Zone Offset into an unique DateTimeOffset.
  5. During the business processing the DateTimeOffset may be converted in other Time Zones, and possibly is rendered again, thus returning to step 1.

Summing up we need:

  • A custom TagHelper to render DateTimeOffset into the 2 input fields format described above
  • Some JavaScript for the conversion in the client Time Zone, and for updating automatically the hidden field
  • A Custom Model for DateTimeOffset types
  • Some wire up code to “connect” our custom model binder.

The above steps are a kind of standard, since custom model binders are always designed together with their compatible rendering counterparts.

A Custom TagHelper for DateTimeOffset

As a first step let create a new asp.net core project named “FixedRepresentationModelBinding” and let select “no authentication”.

Then create a new Folder called “TagHelpers”, and add a new DateTimeOffsetInputTagHelper class.

Our TagHelper should execute before the Asp.net Mvc standard input  TagHelper and should intercept all DateTimeOffset rendering:

 

using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace FixedRepresentationModelBinding.TagHelpers
{
    [HtmlTargetElement("input", Attributes = ForAttributeName,
        TagStructure = TagStructure.WithoutEndTag)]
    public class DateTimeOffsetInputTagHelper : TagHelper
    {
        public override int Order
        {
            get
            {
                return int.MinValue;
            }
        }
        private const string ForAttributeName = "asp-for";
        [HtmlAttributeName("type")]
        public string InputTypeName { get; set; }
        [HtmlAttributeName("value")]
        public string Value { get; set; }

        [HtmlAttributeName(ForAttributeName)]
        public ModelExpression For { get; set; }

        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if(For.Metadata.UnderlyingOrModelType == typeof(DateTimeOffset))
            {
                var fullName = ViewContext.ViewData
                    .TemplateInfo.GetFullHtmlFieldName(For.Name);
                var dvalue = (DateTimeOffset?)For.Model;
                var offset = dvalue.HasValue ?
                    Convert.ToInt32(dvalue.Value.Offset.TotalMinutes) :
                    0;
                if (String.IsNullOrEmpty(InputTypeName))
                    InputTypeName = "datetime-local";
                if (!output.Attributes.ContainsName("type"))
                    output.Attributes.Add("type", InputTypeName);

                if (String.IsNullOrEmpty(Value))
                {
                    Value= dvalue.HasValue ?
                        string.Format("{0:00}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00}",
                        dvalue.Value.Year, dvalue.Value.Month, dvalue.Value.Day,
                        dvalue.Value.Hour, dvalue.Value.Minute, dvalue.Value.Second) :
                        string.Empty;
                }
                if (!output.Attributes.ContainsName("value"))
                    output.Attributes.Add("value", Value);
                output.Attributes.Add("data-has-offset", "true");

                fullName = fullName.Length > 0 ? fullName + ".O" : "O";
                output.PostElement.AppendHtml("<input name='" +
                    fullName + "' type='hidden' value='"+offset+"' />");
            }
        }
    }
}

The Order property returning int.MinValue ensures that out TagHelper is the first to be executed.

The InputTypeName property is filled with the   input “type” if any is specified. If no type is specified it is automatically set to “datetime-local” and copied into the output attributes dictionary

Similarly, if no input “value” is specified, value is taken from the model contained in the For property, serialized with the yyyy-MM-ddTHH:mm:ss format (the format required by a datetime-local input field) and copied to the output dictionary.

The input field itself is not rendered by our TagHelper since its rendering is left to the standard input TagHelper that is executed immediately after our custom TagHelper. However,

the standard TagHelper will use the value and type we have set in the output attributes.

We add the attribute “data-has-offset=’true’” to the output attributes in order to retrieve all DateTimeOffset/rendering input fields from JavaScript.

The last instruction adds further Html to the Html rendered by the standard TagHelper, with the help of PostElement.AppendHtml. This way we add the input type hidden containing the Time Zone offset. The offset is expressed in minutes, since some time zones have an hours+minutes format. Finally, hidden input name is the same as the main input name but with a “.O” postfix.

For more information about custom TagHelpers, please refer to the official documentation.

Now we need to register all TagHelpers contained in the web site dll. Open the _ViewImports.cshtml file contained in the Views folder and add the following line:

@addTagHelper *, FixedRepresentationModelBinding

Now we can test our TagHelper.

Go to “Views\Home\Index.cshtm” and replace the whole content with:

@model Nullable<DateTimeOffset>

@{
    ViewData["Title"] = "Fixed representation Model Binding Test";
    var datetimeTest = Model;
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home">
    <div class="form-group">
        <label asp-for="@datetimeTest">Local date/time:</label>
        <input asp-for="@datetimeTest" class="form-control">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Model must be assigned to the variable datetimeTest otherwise the input field would have empty name and id.

This problem arises because in our very simple test the DateTimeOffset struct is not a property of a bigger model. With our trick the input field is named “datetimeTest” that must match the name of the parameter of the Home controller Index method, that we are going to substitute in the Home controller:

public IActionResult Index(DateTimeOffset? datetimeTest)
        {
            //datetimeTest = new DateTimeOffset(2000, 12, 2, 20, 0, 0,
            //    new TimeSpan(0, 5, 0, 0));
            return View(datetimeTest);
        }

In order to verify that our TagHelper is actually able to render a DateTimeOffset just un-comment the commented lines and run the project. If the selected browser supports datetime-local Httml5 inputs you should see a well formatted date+time. Moreover, looking at the Html sources the hidden input should contain 300 (5 hours times 60 minutes)

If everything is ok, comment again the un-commented lines.

Now is time to add the needed JavaScript. For simplicity, we may add it with an in-line script:

@section scripts{
    <script type="text/javascript">
        (function ($) {
            function dateFromISO8601(isoDateString) {
                var parts = isoDateString.match(/\d+/g);
                var isoTime = Date.UTC(parts[0], parts[1] - 1,
                    parts[2], parts[3], parts[4], parts[5]);
                var isoDate = new Date(isoTime);
                return isoDate;
            }
            function localDateFromISO8601(isoDateString) {
                var parts = isoDateString.match(/\d+/g);
                var isoDate = new Date(parts[0], parts[1] - 1,
                    parts[2], parts[3] || 0, parts[4] || 0, parts[5] || 0);
                

                return isoDate;
            }
            $("[data-has-offset]").each(function () {
                var jThis = $(this);
                var val = $.trim(jThis.val())
                var date = val ? dateFromISO8601(val) : null;
                //now we date have UTC + Server offset
                //since val is interpreted as UTC date but is not
                if (date) {
                    var offset = parseInt(this.nextElementSibling.value);
                    
                    date = new Date(date.getTime()
                        - offset * 1000 * 60);
                    //after subtracting server offset we have right date
                    var clientOffset = -date.getTimezoneOffset();
                    //we change sign because getTimezoneOffset returns UTC-local time
                    //while we need local time - UTC
                    this.nextElementSibling.value = clientOffset;
                    date = new Date(date.getTime()
                        + clientOffset * 1000 * 60);
                    //We add client offset because toISOString
                    //serialize UTD date not local date so we need to increase
                    //UTC date + clientOffset
                    jThis.val(date.toISOString().substr(0, 19));
                }
            })
            .change(function(evt){
                var target=evt.target;
                var val = target.value.trim();
                if (val) {
                    target.nextElementSibling.value =
                       -localDateFromISO8601(val).getTimezoneOffset();
                    //We must call localDateFromISO8601 because date is in local time
                    
                }
            });
        })(jQuery)
    </script>
}

We select all input fields with the “data-has-offset” attribute, that are the ones to process. First of all we convert the DateTime/Time-Zone-Offset pairs into the client time zone. Dates math is done by converting everything in milliseconds: the date with get Time, and the offset by multiplying it times 60*1000. Then we apply a change event handler to all selected inputs, in order to update the Time Zone offset each time the date+time changes.

A Custom Model Binder for DateTimeOffset

Custom model binders for “fixed representations” usually mimic the standard Mvc SimpleTypeModelBinder, the only difference being that the SimpleTypeModelBinder processes just one input field while “fixed representations” model binders process several input fields. As you can see in the source code the SimpleTypeModelBinder uses TypeConverters to deserialize types; for our simple model binder, instead, a DateTime and an integer parsers will be enough.

Let add a new “ModelBinding” folder and create a DateTimeOffsetModelBinder class. Our model binder must implement the interface IModelBinder that contains the single method BindModelAsync:

using System;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace FixedRepresentationModelBinding.ModelBinding
{
    public class DateTimeOffsetModelBinder: IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            var valueProviderResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            var auxValueProviderResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName+".O");
            if (valueProviderResult == ValueProviderResult.None ||
                auxValueProviderResult == ValueProviderResult.None)
            {
                // no entry found for some of the two needed input fields
                //return without setting result, that is, return a failure
                return TaskCache.CompletedTask;
            }
            //store value retrieved for Date+Time in model state
            //this way, in case of format errors user may
            //correct input. No need to store also time zone offset,
            //since it cannot be edited by the user
            bindingContext.ModelState
                .SetModelValue(bindingContext.ModelName, valueProviderResult);

            try
            {
                var value = valueProviderResult.FirstValue;
                var auxValue = auxValueProviderResult.FirstValue;
                object model;
                if (string.IsNullOrWhiteSpace(value) ||
                    string.IsNullOrWhiteSpace(auxValue))
                {
                    //empty fields, means null model
                    model = null;
                }
                else
                {
                    int offset = int.Parse(auxValue, CultureInfo.InvariantCulture);
                    DateTime dt = DateTime.Parse(value, CultureInfo.InvariantCulture);
                    model = new DateTimeOffset(dt, new TimeSpan(0, offset, 0));
                }
                //if model is null and type is not nullable
                //return a required field error
                if (model == null &&
                    !bindingContext.ModelMetadata
                        .IsReferenceOrNullableType)
                {
                    bindingContext.ModelState.TryAddModelError(
                        bindingContext.ModelName,
                        bindingContext.ModelMetadata
                        .ModelBindingMessageProvider.ValueMustNotBeNullAccessor(
                            valueProviderResult.ToString()));

                    return TaskCache.CompletedTask;
                }
                else
                {
                    bindingContext.Result =
                        ModelBindingResult.Success(model);
                    return TaskCache.CompletedTask;
                }
            }
            catch (Exception exception)
            {
                //in case parsers throw a FormatException
                //add error to the model state.

                bindingContext.ModelState.TryAddModelError(
                    bindingContext.ModelName,
                    exception,
                    bindingContext.ModelMetadata);

                
                return TaskCache.CompletedTask;
            }
        }
    }
}

As a first step we use the value provider passed in the bindingContext to get the string values of our two input fields. If provided we use them to build a DateTimeOffset structure with the help of DateTime and int parse methods. In case of errors an error message is added to the ModelState. If the model binder returns TaskCache.CompleteTask without setting bindingContext.Result the framework assumes that model binding failed.

Installing Our Model Binder

There are various options to inform the framework on when to use our model binder:

  1. Decorate a ViewModel property or an Action Method parameter with a ModelBinderAttribute specifying the type of our model binder. In this case just that property or parameter will be bound with our model binder.
  2. Decorate the class or struct to bind with our model binder with the ModelBinderAttribute. In this case the model binder is used for each occurrence of the target type. Unluckily, we can’t follow this path since DateTimeOffset is a system type, so we can’t apply any attribute to it.
  3. Installing the model binder in the standard model binding pipeline. Also in this case the model binder is used for each occurrence of our target type.

Since we want our model binder be used on each occurrence of DateTimeOffset structures, and since option 2 is not viable we are forced to adopt option 3. Since in option 3 the model binder is not attached to any type or property we must instruct explicitly the standard model binding pipeline on when to use our model binder. This is done by defining an implementation of the IModelBinderProvider interface that exposes the single GetBinder method. Let call DateTimeOffsetModelBinderProvider our implementation, and place it in the already defined “ModelBinding” folder:

using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace FixedRepresentationModelBinding.ModelBinding
{
    public class DateTimeOffsetModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.UnderlyingOrModelType == typeof(DateTimeOffset))
            {
                return new DateTimeOffsetModelBinder();
            }

            return null;
        }
    }
}

The implementation is straightforward, if the current type to bind is either a DateTimeOffset or a DateTimeOffset? our provider returns an instance of our model binder, otherwise it returns null. A null result informs the model binding pipeline to try the next IModelBinderProvider implementation.

In fact all installed IModelBinderProvider implementations are placed into an IList contained in the ModelBinderProviders property of the MvcOptions object. Accordingly, we may have our model binder working by adding its associated provider to this IList.

The MvcOptions default object may be modified in several ways, The easiest way being to substitute:

services.AddMvc()

in the Startup.cs class, with:

services.AddMvc(o =>
{
    o.ModelBinderProviders.Insert(0, new DateTimeOffsetModelBinderProvider());
});

 

 

We added our provider on top of the list so it is tried first, to avoid that some other “standard” provider might select a different model binder.

Done!

Run the application, and when the home page appears, place a breakpoint in the Index method of Home controller that will receive our submitted data. Now select select a date+time, submit and verify what is received by the Index method: a DateTimeOffset containing the date and time selected in the browser, an the right client Time Zone offset!

That’s all for now

In a short time the last episode of our series: model binding interfaces!

Stay tuned!

Francesco

Tags: , ,

Feb 5 2017

Don’t miss MVP led TechDays Online!

600x600-TechDaysOnline-Claire-Smyth-Illustration-V2

Hear from leading MVPs and technical experts talking about:

20 February 2017

  • 10.00am: Data, data, data – How and Where to store it on Azure?
  • 11.00am: Conversational UI using the Microsoft Bot Framework
  • 12.00pm:Microsoft Bot Framework and Cognitive Services: Make your bot smarter!
  • 1.00pm: The best kept secret, Document DB
  • 2.00pm: Let’s discuss Server-less
  • 3.00pm: What is an Azure Data Lake?
  • 4.00pm Close

21 February 2017

  • 10.00am: Creating a PHP-MySQL web app in Azure App Service and deploying using FTP. MVP Rik Hepworth
  • 11.00am: Gain profit from Azure app service tooling as an OSS developer. MVP Mike Martin
  • 12.00pm: Dockerizing Your Cross-Plat .NET Development. MVP Rainer Stropek
  • 1.00pm: Communication Driven Development. Jessica Rose
  • 2.00pm:  Monitoring Linux in Azure with Microsoft Operations Management Suite Log Analytics. MVP Gordon McKenna
  • 3.00pm: The Open Source World of Xamarin. MVP Garry Whittaker
  • 4.00pm Close

22 February 2017

  • 10.00am: Bootstrapping blockchain. Microsoft’s Mike Ormond and Jonathan Collinge 
  • 11.00am:  How IOT and data is changing lives. Haiyan Zhang from Microsoft Research
  • 12.00pm: An introduction to Quantum Computing. Ilyas Khan from Quantum Computing
  • 1.00pm: Social Scientist Professor Bradley Love from University College London and the Alan Turing Institute
  • 2.00pm: Microsoft Regional Directors panel. Richard Conway, Andy Cross, Steve Thair and Simon Sabin
  • 3.00pm: Close

Tags: , , ,

Jan 29 2017

Custom Model Binding in Asp.net Core Mvc, 1

Category: Asp.net core | Asp.net | MVCFrancesco @ 06:48


Custom Model Binding in Asp.net Core, 2: Getting Time + Client Time Zone Offset

Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces

This is the first of a series of 3 posts on how to write custom model binders in Asp.net core Mvc. Three posts on three different ways to customize model binding in three different scenarios.

The concept of “simple type” plays a key role in model binding. A Simple type is not just a string, numbers, dates, or any other.net basic type but any type we decide to render as a string in a single input field. Below three examples of types that’s worth to render as “simple types”:

  1. An YouTube Url type, that contains the id of the you tube Url, but is rendered as an actual Url according to some format settings (it might implement IFormattable, for instance), and that “Model Binds” any correct YouTube Url.
  2. A Month type that contains month and year information and that is rendered in Month ISO format (YYYY-MM) into an HTML5 Month input.
  3. A Week type that contains week and year information and that is rendered in Week ISO format (YYYY-Www)  into an HTML5 Week input.

However, we may represent as “simple types” arbitrarily complex data structures by converting them from/to single strings in JSON format. Thus, they are “simple” just because they fit an a single input field.

Types that are not simple are “complex”. In turns, complex types may be split into 2 categories: fixed representation types, and variable representation types. Fixed representation types are rendered with a constant number of input fields whose names do not depend on the value of each instance. Roughly, they are always rendered with the “same input fields”.

For instance, we may represent the Month type mentioned above also as a fixed representation complex type using an input field for the year and another input field for the month.

IEnumerables and generic types must be considered variable representation types if their properties are rendered in different input fields. However, they may always be worked as simple types by using a single input field and JSON serialization.

Simple types, fixed representation types and variable representation types need different model binding techniques.

Variable representation types are the more difficult to deal with and will be analyzed in the last post of the series, since, in general, they require the model binder be invoked recursively to bind their sub-parts.

Simple types are the easier to model bind since it is enough to specify how they must be serialized and de-serialized. The remainder of this post is dedicated to them. We use the Month type example.

As a first step let create a new asp.net core project named “SimpleModelBinding” and let select “no authentication”.

Then create a new Folder called “Types”, and add a new Month structure:

public struct Month
{
    public uint YearNumber { get; private set; }
    public uint MonthNumber { get; private set; }
   

    public Month(uint yearNumber, uint monthNumber)
    {
        YearNumber = yearNumber;
        MonthNumber = monthNumber;
        if (MonthNumber < 1 || MonthNumber > 12) throw new FormatException();
        if (yearNumber < 1) throw new FormatException();
    }
    public static Month MinValue { get { return new Month(1, 1); } }
    public static Month MaxValue { get { return new Month(9999, 12); } }
}
Add conversion to/from DateTime:
public DateTime ToDateTime()
{
    return new DateTime((int)YearNumber, (int)MonthNumber, 1);
}

public static Month FromDateTime(DateTime t)
{
    return new Month((uint)t.Year, (uint)t.Month);
}

public static implicit operator Month(DateTime t)
{
    return FromDateTime(t);
}

public static implicit operator DateTime(Month m)
{
    return m.ToDateTime();
}

Finally add also ToString and Parse methods:

public override string ToString()
{
    return string.Format("{0:0000}-{1:00}", YearNumber, MonthNumber);
}

public static Month Parse(string s)
{
    return FromDateTime(DateTime.Parse(s));
}

public static bool TryParse(string s, out Month m)
{
    DateTime dt;
    var res = DateTime.TryParse(s, out dt);
    if (res) m = FromDateTime(dt);
    else m = new Month(1, 1);
    return res;
}

Add month and year may be useful too:

public Month AddMonths(int months)
{
    if (months == 0) return this;
    months = (int)MonthNumber + months;
    var years = months / 12;
    months = months % 12;
    if (months < 0)
    {
        months += 12;
        years--;
    }
    return new Month((uint)(years + YearNumber), (uint)(months));

}
public Month AddYears(int years)
{
    return new Month((uint)(YearNumber + years),
        MonthNumber);
}

If you want you may also define all comparison operators.

Since we already have adequate parsing and ToString methods we are very close to our goal.

We need just to inform Asp-net core Mvc model binding engine on which functions to call to serialize/de-serialize the Month type. This, doesn’t require the definition of a custom model binder but the definition of a TypeConverter that is able to convert between Month and string. In fact, Asp-net core Mvc model binding engine assumes that a type is “simple” exactly when a similar TypeConverter exists.

Let add a new class called MonthTypeConverter to our Types folder:

using System;
using System.ComponentModel;
using System.Globalization;

namespace SimpleModelBinding.Types
{
    public class MonthTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context,
            Type sourceType)
        {
            return sourceType == typeof(string) ||
                sourceType == typeof(DateTime);
        }
        public override object ConvertFrom(ITypeDescriptorContext context,
            CultureInfo culture, object value)
        {
            return value is string ? Month.Parse(value as string) :
                Month.FromDateTime((DateTime)value);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context,
            Type destinationType)
        {
            return destinationType == typeof(string) ||
                destinationType == typeof(DateTime);
        }
        public override object ConvertTo(ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
                return ((Month)value).ToString();
            return ((Month)value).ToDateTime();
        }
    }
}

The code is self explicative two bool functions that return true if the conversion from/to a type is possible and two functions that actually perform the conversion from/to. I enabled conversion from/to both DateTime and string but for the purpose of model binding conversion from strings is enough.

Now let declare that this type converter is associated with the Month struct by decorating the Month definition as shown below:

[System.ComponentModel
    .TypeConverter(typeof(MonthTypeConverter))]
public struct Month
{
    ...
    ...

Done! Now we need just to test our Month struct.

Go to the HomeController and substitute the Index method with:

 

public IActionResult Index(Nullable<Month> monthTest)
{
    return View(monthTest);
}

Then go to “Views\Home\Index.cshtm” and replace the whole content with:

@model Nullable<SimpleModelBinding.Types.Month>
@{
    ViewData["Title"] = "Simple Type Model Binding Test";
    var monthTest = Model;
}

<h2>@ViewData["Title"]</h2>

<form asp-action="Index" asp-controller="Home" >
    <div class="form-group">
        <label asp-for="@monthTest">Month:</label>
        <input asp-for="@monthTest" type="month" class="form-control">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

Model must be assigned to the variable monthTest otherwise the input field would have empty name and id.

This problem arises because in our very simple test the month struct is not a property of a bigger model. With our trick the input field is named “monthTest” that must match the name of the parameter of the Home controller Index method.

Now select a browser that supports input of type Month (last versions of Edge, Safari, Chrome, Firefox, will do) and run the project.

Select a month, and before submitting place a breakpoint in the Index action method. Once the breakpoint is hit you should see that the month parameter contains the month you have chosen in the browser:

SimpleModelBinderDebug

 

 

 

 

 

In a similar way you might define a Week type and a custom model binding for it.  The Asp.net core version of the Mvc Controls Toolkit, contains Week and Month types together with custom model binding, extensions of RangeAttribute and all validation rules, fallbacks for browsers that do not support any HTML5 and more…

 

That’s all for now

In a short time the second post of our series.

Stay tuned!

Francesco

Tags: , , ,

Jan 2 2017

Defining Custom Client Validation Rules in Asp.net Core MVC

Category: Asp.net | Asp.net core | MVCFrancesco @ 22:15

This time my post has been published on the MSDN Blog! Enjoy it!

……..The way Asp.net MVC handles client side validation has relied on unobtrusive validation since Asp.net MVc 3. All client validation rules for each input field are extracted from various sources, including validation attributes, and the type of property to be rendered and encoded in the content of Html5 data…….Read full article

Tags: , , , ,

Nov 20 2015

New Mvc6 Controls Toolkit

Category: TypeScript | JavaScript | MVC | Asp.netFrancesco @ 04:50

Web development changed dramatically in the last few years and the Mvc Controls Toolkit team run after all changes to offer a state of the art toolkit, but now it is time to redesign the whole toolkit from the scratch! JavaScript world evolved, and web applications reliy always more on client side techniques. New JavaScript frameworks appears and evolve quickly, thus the need of a better separation between server side and client side world. The new Mvc 6 Controls Toolkit answers to these new Web Development boundaries are: TypeScript, a better separation of JavaScript world coordinated with server side C# code through trans-compilation of C# classes and attributes, native support of the most common client side frameworks like Angular.js, and Knockout.js, and open support for other client side framework by means of providers,…and more!

 

Please leave you feedback on the specifications of the new Mvc 6 Controls Toolkit!

 

Francesco

Tags: , , , , , , ,