开发者

ASP.NET MVC 2 - Handling files in an edit action; Or, is it possible to create an 'Optional' data annotation which would skip over other attributes?

I've run into a bit of a design issue, and I'm curious if anyone else has run into something similar.

I have a fairly complex model which I have an Edit action method for. Each individual entity has two images associated with it, along with other, more mundane data. These images are [Required] upon creation. When editing an entity, however, these images already exist, since, again, they were required upon creation. Thus, I don't need to mark them as required.

Adding a bit of a monkey wrench to the whole thing is my custom image validation attribute:

public class ValidateFileAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var file = value as HttpPostedFileBase;

        if (file == null)
        {
            return false;
        }

        string[] validExtensions = { "jpg", "jpeg", "gif", "png" };
        string[] validMimeTypes = { "image/jpeg", "image/pjepeg", "image/gif", "image/png" };

        string[] potentialFileExtensions = file.FileName.Split('.');
        string lastExtension = potentialFileExtensions[(potentialFileExtensions.Length - 1)];
        string mimeType = file.ContentType;

        bool extensionFlag = false;
        bool mimeFlag = false;

        foreach (string extension in validExtensions)
        {
    开发者_StackOverflow社区        if (extension == lastExtension)
            {
                extensionFlag = true;
            }
        }

        foreach (string mt in validMimeTypes)
        {
            if (mt == mimeType)
            {
                mimeFlag = true;
            }
        }

        if (extensionFlag && mimeFlag)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

What I'd ideally like to do would be to create some kind of [Optional] attribute which would bypass the image validator altogether if new files aren't POSTed along with the rest of the form data.

Is something like this possible? If not, how would the collective wisdom of Stack Overflow address the problem?


you might be interested in following article... but i have to say i do agree with most in the article.

mainly the part : conditional validation

http://andrewtwest.com/2011/01/10/conditional-validation-with-data-annotations-in-asp-net-mvc/

hope this will helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜