Добрый вечер. Есть форма : Код | @using (Ajax.BeginForm("SendDialogMessage", "Messages", null, new AjaxOptions { OnSuccess = "OnSendDialogLoad" }, new { @id = "f_NewMessage", @class = "", @enctype = "multipart/form-data" })) {
@Html.Hidden("url", Request.Url.OriginalString) @Html.Hidden("hid_Receiver", sId) @Html.Hidden("hid_IsConference", bIsConference) <input type="submit" value="submit" style="display:none;" /> @Html.TextArea("ta_NewMessage_Text", new { placeholder = "Введите тест сообщения", onkeydown = "ta_NewMessage_Text_OnKeyDown(event);" }) <div id="d_NewMessage_Buttons"> <button id="btn_NewMessage_Find" class="hidden btn_min_Find"></button> <input type="submit" id="btn_NewMessage_Send" onclick="btn_NewMessage_Send_OnClick()" value="Отправить" /> <button id="btn_NewMessage_Attach" class="hidden btn_min_Attach"></button> <div id="d_upload_menu"> <div id="d_file-upload"> <label> <img src="~/Content/images/attach_inMessage.png" width="40" height="40" alt="Выберите файл"> <input type="file" name="uploadFile" id="uploadFile" multiple> </label> </div> <div id="d_dropzone"> <div id="d_dropzone_caption">Перетащите файлы сюда</div> </div> </div>
</div> }
|
Метод обрабатывающий данные с формы: Код | [HttpPost] [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] public ActionResult SendDialogMessage(FormCollection collection) { try { foreach (string file in Request.Files) { var upload = Request.Files[file]; if (upload != null) { string fileName = System.IO.Path.GetFileName(upload.FileName); Dictionary<string, byte[]> files = new Dictionary<string, byte[]>(); byte[] File = new byte[upload.ContentLength]; upload.InputStream.Read(File, 0, upload.ContentLength); files.Add(fileName, File); //upload.SaveAs(Server.MapPath("~/" + fileName)); } }
var returnAction = CheckCurrentUser(); if (returnAction != null) return returnAction;
Guid? SenderId = CurrentUserId; ViewBag.CurrentUserId = CurrentUserId; if (SenderId == null) return View("_ErrorAuth");
Users tempUser = new Users(); Guid ReceiverId; bool IsConference = Convert.ToBoolean(collection["hid_IsConference"]);
if (!Guid.TryParse(collection["hid_Receiver"], out ReceiverId)) { return Error("Ошибка. Неверный идентификатор получателя."); } string messText = collection["ta_NewMessage_Text"]; v_messages MessageInfo; byte[] attached = null; Guid messageId = Guid.NewGuid(); Guid messageLogId = Guid.NewGuid();
using (var chatclient = ChatClientService.CreateChatClient()) { var err = chatclient.Send((Guid)SenderId, ReceiverId, IsConference, messText, attached, out MessageInfo); // var err = chatclient.Send((Guid)SenderId, ReceiverId, message, attached, out MessageInfo); if (err != EChatError.Ok || MessageInfo == null) return Error("Ошибка сервиса. Не удалось отправить сообщение."); // ReturnMessage m = new ReturnMessage(MessageInfo);
return View("_Message", MessageInfo); } } catch (Exception e) { return Error("Ошибка. Не удалось отправить сообщение." + e.Message); } }
|
Возникла необходимость добавить файлы к сообщению. Написал такой js код: Код |
var data = new FormData(); var countfile = 0; var idFile = 0; //удаление выбранного файла function DeleteFile(id) { var file = "file" + id; $("div." + file).remove(); data.delete(file); } //перетаскивание файла (function () { var dropzone = document.getElementById("d_dropzone"); var dropzone_caption = document.getElementById("d_dropzone_caption"); dropzone.ondragover = function () { return false; };
dropzone.ondragleave = function () { return false; };
dropzone.ondrop = function (e) { e.preventDefault(); var files = e.dataTransfer.files; for (var x = 0; x < files.length; x++) { document.getElementById('d_dropzone').innerHTML += '<div class="file' + idFile + '"><p>' + files[x].name + ' (' + files[x].size + '.КБ)</p><label><img onclick="DeleteFile(' + idFile + ')" src="Content/images/delete.png" width="20" height="20" alt="удалить"></label> <b></b></div>'; data.append("file" + idFile, files[x]); idFile++; } }; })(); //выбор файла $('#uploadFile').on('change', function (e) { e.preventDefault(); var files = document.getElementById('uploadFile').files; if (files.length > 0) { if (window.FormData !== undefined) { for (var x = 0; x < files.length; x++) { document.getElementById('d_dropzone').innerHTML += '<div class="file' + idFile + '"><p>' + files[x].name + ' (' + files[x].size + '.КБ)</p><label><img onclick="DeleteFile(' + idFile + ')" src="Content/images/delete.png" width="20" height="20" alt="удалить"></label> <b></b></div>'; data.append("file" + idFile, files[x]); idFile++; } } else { alert("Браузер не поддерживает загрузку файлов HTML5!"); } } }); window.addEventListener("submit", function (e) { var form = e.target; if (form.getAttribute("enctype") === "multipart/form-data") { if (form.dataset.ajax) { e.preventDefault(); e.stopImmediatePropagation(); var dataForm = new FormData(form); dataForm.delete('uploadFile'); for (var key of data.keys()) { dataForm.append(key, data.get(key)); } idFile = 0; data = new FormData(); document.getElementById('d_dropzone').innerHTML = '<div id="d_dropzone_caption">Перетащите файлы сюда</div>'; var xhr = new XMLHttpRequest(); xhr.open(form.method, form.action); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (form.dataset.ajaxUpdate) { var updateTarget = document.querySelector(form.dataset.ajaxUpdate); if (updateTarget) { updateTarget.innerHTML = xhr.responseText; } } } }; xhr.upload.onerror = function () { alert('Произошла ошибка при загрузке данных на сервер!'); } xhr.send(dataForm); } } }, true);
|
Теперь при отправке сообщения страница не обновляется автоматически (приходится самому обновлять страницу, чтобы увидеть введенное сообщение). До добавления данного js кода все работало нормально. Я предполагаю что проблема в ф-и window.addEventListener("submit", function (e) {...} Помогите кто знает в чем проблема и как её решить. Заранее благодарен.
|