Search code examples
javascriptc#jqueryasp.net-mvc-4unobtrusive-validation

jQuery Validation and Image file


Ok I have situation where i am posting my image file to server but before that i verify it whether user selects the file or not using "required" attribute. Also previewing image using java funtion . now problem is in case of edit mode when information is loaded to page i obviously not loading the image file instead i just create the preview path and assign it to imagepath. So when i save the information after editing it again ask me "image is required". system is right because i have not selected any image. how do i resolve this issue? i want to enforce jquery validation but in case of edit mode it should skip image validation step.

Script

<script>
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();            
        reader.onload = function (e) {
            $('#imgpreview1').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#file").change(function () {
    readURL(this);
});


<script/>                    

View

@Html.Label("Venue Description Background") 
@Html.TextBoxFor(model => model[0].Image.ImageFile, new { type = "file", id="file", required="required"})

<img src="@Model[0].Image.ImagePath" id="imgpreview1"  style="height:150px;width:150px"/>

Model

   public iSPYImage Image { get; set; }

    [DisplayName("Image File")]
    public HttpPostedFileBase ImageFile{ get; set;}

Solution

  • Use some condition in the view definition. something like:

    if(editMode)
         @Html.TextBoxFor(model => model[0].Image.ImageFile, new { type = "file",        id="file"})
    else
         @Html.TextBoxFor(model => model[0].Image.ImageFile, new { type = "file", id="file", required="required"})