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?

主宰稳场 提交于 2019-12-11 03:22:20

问题


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)
        {
            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?


回答1:


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.



来源:https://stackoverflow.com/questions/7212053/asp-net-mvc-2-handling-files-in-an-edit-action-or-is-it-possible-to-create-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!