New to Telerik UI for Blazor? Download free 30-day trial

Validation from a model is extended with the MetadataTypeAttribute does not work

Environment

Product Grid for Blazor

Description

All of our Models are Generated via EF Scaffolding. We need to be able to specify our Validation criteria using the MetadataTypeAttribute and partial classes, but the validation is not honored in the Telerik components.

Possible Cause

The grid needs to create a new instance of the model for inserting or editing, and the only way to do that is to use Activator.CreateInstance(). This does not take into account the custom metadata type from the partial classes however, so the model that it returns does not have data annotations at all, and so - no validation or other attributes.

You can reproduce this behavior with the following simplistic markup without any Telerik components.

@using System.ComponentModel.DataAnnotations;

<EditForm Model="@cust" OnValidSubmit="@ValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="@cust.Title"></InputText>

    <button type="submit">VALIDATE</button>
</EditForm>

@code{
    Customer cust { get; set; }

    protected override void OnInitialized()
    {
        //this mimics what the grid does to get an instance of the model to be edited/inserted
        cust = Activator.CreateInstance(typeof(Customer)) as Customer;

        base.OnInitialized();
    }

    void ValidSubmit()
    {
        Console.WriteLine("Valid submit");
    }

    // partial class from the app to point to custom metadata class
    [MetadataType(typeof(CustomerMetaData))]
    public partial class Customer
    {

    }

    // the custom metadata class
    public class CustomerMetaData
    {
        [Required(ErrorMessage = "Title is required.")]
        public object Title;
    }

    // mockup of what could be generated by EF
    public partial class Customer
    {
        public string Title { get; set; }
    }
}

Suggested Workarounds

The Telerik components cannot get an instance of the model in any other way, so there can be two potential options:

  • Create a custom edit form (inline or popup) where you can implement the model generation and validation as required in a way that works for your project.

  • If you have the same models and can create an instance that has the desired validation, you can try setting it through the grid state to initiate insertion or editing for a particular model instance, rather than let the grid create it.

In this article