Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Това ми е частта от PartialView-to в MVC проекта, отговорна за ъплоудването на файлове:
- <div id="drop-zone">
- <div id="clickHere">
- Select file... <i class="fa fa-upload"></i>
- <input type="file" name="fileUpload" id="fileUpload" multiple="multiple" />
- </div>
- <div id='filename'></div>
- </div>
- Това ми е js файла в него добавям файлове, изтривам и прихващам когато се натисне бутона събмит вместо да се извиква стандартния mvc събмит - изпращам ajax с данните от формата и прикачените файлове:
- var filesCollection = [];
- var fileCounter = 0;
- $(function () {
- var dropZoneId = "drop-zone";
- var mouseOverClass = "mouse-over";
- var dropZone = $("#" + dropZoneId);
- var inputFile = dropZone.find("input");
- document.getElementById(dropZoneId).addEventListener("drop", function (e) {
- $("#" + dropZoneId).removeClass(mouseOverClass);
- }, true);
- inputFile.on('change', function (e) {
- var fileNum = this.files.length,
- fileNames = "";
- var fileInput = $('#fileUpload').prop('files')[0];
- fileNames = this.files[0].name + ' ';
- var newFileZone = '<div id="file_' + fileCounter + '"><span><strong style="color:#FFF; font-size:12px; margin-top:2px;">' + fileNum + '</strong></span><span>' + fileNames + '</span> <span class="closeBtn btn btn-danger btn-xs" title="remove" onClick="removeFile(' + fileCounter +');">X</span></div>';
- $('#filename').append(newFileZone);
- filesCollection.push({
- key: ('file_' + fileCounter),
- value: fileInput
- });
- fileCounter = fileCounter + 1
- });
- });
- function removeFile(fileCounter) {
- $('#file_' + fileCounter).remove();
- filesCollection = filesCollection.filter(item => item.key !== 'file_' + fileCounter)
- }
- $('#submitBtn').click(function (e) {
- e.preventDefault();
- var params = $('form').serializeArray();
- var formData = new FormData();
- var filesCount = Object.keys(filesCollection).length;
- for (i = 0; i < filesCount; i++) {
- var fileToAppend = filesCollection[i].value;
- formData.append('files', fileToAppend);
- }
- $(params).each(function (index, element) {
- formData.append(element.name, element.value);
- });
- if ($('form').valid()) {
- $.ajax({
- type: "POST",
- url: ("/Administrator/Prospect/Create"),
- processData: false,
- contentType: false,
- dataType: "JSON",
- data: formData,
- async: false,
- error: function (req, err) { console.log('my message' + err); }
- });
- }
- });
- Проблема ми е че ми трябва валидация на полетата, която направих с jquery unobtrusive validation. Но той се изпълнява при натискане на бутона събмит.. И съответно нямам валидация.
- Всяка идея/насока от твоя страна ще ми бъде от огромна полза :)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement