ASP.NET DynamicData Validate Custom Image FieldTemplate

575 Views Asked by At

I've created a custom Image Field Template which works fine. I decided to create some kind of validation for image sizes so I've created a custom validation attribute. here is the code:

public class ImageSizeValidator : ValidationAttribute
{
    public long MaxSize { get; set; }
    public long MinSize { get; set; }

    public override bool IsValid(object value)
    {
        if (value == null)
            return true;

        byte[] image = (byte[]) value;

        if (image.Length / 1024L > MaxSize || image.Length / 1024L < MinSize)
            return false;

        return true;
    }
}

and here is my FieldTemplate Image_Edit.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Image_Edit.ascx.cs" Inherits="RastinArgham.CRM.Web.DynamicData.FieldTemplates.Image_Edit" %>

<asp:FileUpload ID="FileUpload1" runat="server" OnDataBinding="FileUpload1DataBinding" />

<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="FileUpload1" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="FileUpload1" Display="Static" />

and here is Image_Edit.ascx.cs:

public partial class Image_Edit : System.Web.DynamicData.FieldTemplateUserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SetUpValidator(RequiredFieldValidator1);
        SetUpValidator(DynamicValidator1);
    }

    protected override void ExtractValues(IOrderedDictionary dictionary)
    {
        if (FileUpload1.PostedFile == null || String.IsNullOrEmpty(FileUpload1.PostedFile.FileName) || FileUpload1.PostedFile.InputStream.Length == 0)
            return;

        dictionary[Column.Name] = FileUpload1.FileBytes;
    }

    public override Control DataControl
    {
        get
        {
            return FileUpload1;
        }
    }
}

and finally my entity meta data class:

[Display(Name = "ServicePhoto", Order = 410, GroupName = "Misc")]
[HideColumnIn(PageTemplate.List)]
[UIHint("Image")]
[ImageSizeValidator(ErrorMessage = "Invalid Photo Size", MinSize = 30, MaxSize = 300)]
 public object ServicePhoto { get; set; }

There are two problems:

1- when IsValid(object value) called value is always null!

2- when trying to upload a new image I always get "The value is not valid" Error on client side of validation.

0

There are 0 best solutions below