Search results

Determine whether the Uploader has Input File in ASP.NET MVC Uploader control

08 Dec 2021 / 1 minute to read

By setting required attribute to uploader input element, you can validate the file input has any value in it. In the below sample, set required attribute to the uploader input element and showcase the validation failure message using data-required-message attribute.

razor
required.cs
Copied to clipboard
<div class="col-lg-8 control-section">
    <div class="control_wrapper">
        <div class="col-lg-12 control-section">
            <h4 class="form-title">Photo Contest</h4>
            <div class="control_wrapper" id="control_wrapper">
                <form id="form1" method="post">
                    <div class="form-group" style="padding-top: 40px; float: left">
                        <div class="e-float-input">
                            <input type="text" id="name" name="name" data-required-message="* Enter your name" required="" data-msg-containerid="nameError">
                            <span class="e-float-line"></span>
                            <label class="e-float-text e-label-top" for="name">Name</label>
                        </div>
                        <div id="nameError"></div>
                    </div>
                    <div id="dropArea">
                        <div id="uploadError" style='float: right;'></div>
                        <div id='customBrowse' class="form-group dropUpload">
                            Drop image here...
                            @Html.EJS().Uploader("UploadFiles").DropArea(".dropUpload").Selected("onFileSelect").AllowedExtensions("image/*").Multiple(true).AutoUpload(false).AsyncSettings(new Syncfusion.EJ2.Inputs.UploaderAsyncSettings { SaveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Save", RemoveUrl = "https://ej2.syncfusion.com/services/api/uploadbox/Remove" }).Render()
                        </div>
                    </div>
                    <div class="submitBtn">
                        <button type="button" class="submit-btn e-btn" id="submit-btn">Submit</button>
                        <div class="desc"><span>*This button is not a submit type and the form submit handled from externally.</span></div>
                    </div>
                </form>
                @Html.EJS().Dialog("confirmationDialog").Buttons(ViewBag.DefaultButtons).Width("335px").Visible(false).Content("Your details has been updated successfully, Thank you").Target("#control_wrapper").IsModal(true).AnimationSettings(new Syncfusion.EJ2.Popups.DialogAnimationSettings() { Effect = Syncfusion.EJ2.Popups.DialogEffect.Zoom }).Render()
            </div>
        </div>
    </div>
</div>

<script>
    var formID, confirm;
    window.onload = function () {
        inputElement = document.getElementById('upload');
        formID = document.getElementById('form1');
        confirm = document.getElementById("confirmationDialog").ej2_instances[0];
        formObj = new ej.inputs.FormValidator(formID, options);
        document.getElementById('customBrowse').onclick = () => {
            document.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click();
        };
        document.getElementById('submit-btn').onclick = () => {
            onFormSubmit();
        };
    }
    var options = {
        customPlacement: function (inputElement, errorElement) {
            inputElement = inputElement.closest('.form-group').querySelector('.error');
            inputElement.parentElement.appendChild(errorElement);
        },
        rules: {
            'name': {
                required: true
            }
        }
    };
    function onFileSelect(args) {
        if (args.filesData.length > 0) {
            if (document.getElementsByClassName('upload-image').length > 0) {
                detach(document.getElementsByClassName('imgWrapper')[0]);
            }
            var imageTag = ej.base.createElement('IMG', { className: 'upload-image', attrs: { 'alt': 'Image' } });
            var wrapper = ej.base.createElement('span', { className: 'imgWrapper' });
            wrapper.appendChild(imageTag);
            var rootFile = document.getElementsByClassName('dropUpload')[0];
            rootFile.insertBefore(wrapper, rootFile.firstChild);
            readURL(wrapper, args.filesData[0]);
        }
        args.cancel = true;
    }

    function readURL(li, args) {
        var preview = li.querySelector('.upload-image');
        var file = args.rawFile;
        var reader = new FileReader();
        reader.addEventListener('load', () => { preview.src = reader.result; }, false);
        if (file) { reader.readAsDataURL(file); }
    }
    var options = {};
    formID = document.getElementById('form1');
    var formObj = new ej.inputs.FormValidator(formID, options);
    function onFormSubmit() {
        var formStatus = formObj.validate();
        if (formStatus) {
            formObj.element.reset();
            ej.base.detach(document.getElementsByClassName('imgWrapper')[0]);
            confirm.show();
        }
        document.querySelector('#UploadFiles').setAttribute('data-required-message', '* Choose your image to upload');
        document.querySelector('#UploadFiles').setAttribute('required', '');
        document.querySelector('#UploadFiles').setAttribute('data-msg-containerid', 'uploadError');

    }
    function dlgButtonClick() {
        confirm.hide();
    }

</script>
Copied to clipboard
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace EJ2CoreSampleBrowser.Controllers.TextBoxes
{
    public partial class UploaderController : Controller
    {
        public ActionResult DefaultFunctionalities()
        {
            List<DialogDialogButton> buttons = new List<DialogDialogButton>() { };
            buttons.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonModel = new DefaultButtonModel() { content = "Ok", isPrimary = true } });
            ViewBag.DefaultButtons = buttons;
            return View();
        }

    }
    public class DefaultButtonModel
    {
        public string content { get; set; }
        public bool isPrimary { get; set; }
    }
}

You can also explore ASP.NET MVC File Upload feature tour page for its groundbreaking features. You can also explore our ASP.NET MVC File Upload example to understand how to browse the files which you want to upload to the server.