Hi All,
I have a application that uses both a drag and drop file upload option and a Browse and select file option.
I put these option all on one razor page.
I do this so that I can get information from the user that I can use to tag the file names and email the conformations,
Both options work,
The Drag and drop uploads the files and prints a submit message showing success.
The browse and select works but it clears the fields and resets the page values.
Also it does not update the view bag with the success message.
I am at my wits end with it that's for sure.
I will post screen shots and source codes:
The Blue and Black marked areas are Partial Views that get displayed when the Green Button under the contact information is clicked.
The problem is when the Blue Uploaded Selected Files is clicked the values in the fields highlighted in yellow get cleared out.
No matter what I try I can not seem to be able to preserve those field values.
They are part of a viewmodel.
Here is the controller:
using DOT.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace DOT.Controllers
{
public class LHRController : Controller
{
//See: https://stackoverflow.com/questions/5939353/how-do-you-keep-the-value-of-global-variables-between-different-action-methods-c
private static string GV_FNAME = "";
private static string GV_LName = "";
private static string GV_Email = "";
// GET: LHR
[HttpGet]
public ActionResult LHR()
{
return View();
}
public ActionResult ApplicationUpload( string Style = "display: none")
{
//VM_LHR_ApplicationClass vm_LHR_ApplicationClass = new VM_LHR_ApplicationClass();
//vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
//vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
//vm_LHR_ApplicationClass.CONTACT_EMAIL = GV_Email;
ViewBag.DDAreaPartialStyle = Style;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ApplicationUpload([Bind(Include = "CONTACT_FIRST_NAME,CONTACT_LAST_NAME,CONTACT_EMAIL")] VM_LHR_ApplicationClass vm_LHR_ApplicationClass)
{
try
{
if (ModelState.IsValid)
{
//See The DD_Are Visibility
string Style = "display: block";
//Set Vars
GV_FNAME = vm_LHR_ApplicationClass.CONTACT_FIRST_NAME.ToString();
GV_LName = vm_LHR_ApplicationClass.CONTACT_LAST_NAME;
GV_Email = vm_LHR_ApplicationClass.CONTACT_EMAIL;
//See: https://stackoverflow.com/questions/39725099/how-to-show-your-hidden-partial-view-programmatically-in-mvc
ViewBag.DDAreaPartialStyle = Style;
return View();
}
else
{
string Style = "display: none";
var Errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
TempData["ContactValidationErrors"] = Errors.Count;
ViewBag.DDAreaPartialStyle = Style;
return View();
}
}
catch (Exception e)
{
return PartialView("Error");
}
//return View();
}
//[HttpGet]
// public ActionResult SingleFileUpload()
// {
// string Style = "display: block";
// ViewBag.DDAreaPartialStyle = Style;
// return RedirectToAction("ApplicationUpload");
// }
[HttpPost]
public ActionResult SingleFileUpload(HttpPostedFileBase file)
{
try
{
var EmailResponder = new ApplicationClasses.EmailResponderClass();
//MakeUploadDate No Spaces:
string UploadDate = DateTime.Today.ToString("MM/dd/yy");
UploadDate = UploadDate.Replace("/", string.Empty);
//MakeUniqueTicker See: https://stackoverflow.com/questions/9278909/net-short-unique-identifier
var ticks = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).Ticks.ToString();
//var ans = DateTime.Now.Ticks - ticks;
//var UniqueId = ans.ToString("x").Remove(4,4);
string FileNamePrefix = UploadDate + "__" + LHRController.GV_LName + LHRController.GV_FNAME + "__" + Guid.NewGuid().ToString().Remove(5, 10);// ticks.Remove(5, 11);
VM_LHR_ApplicationClass vm_LHR_ApplicationClass = new VM_LHR_ApplicationClass();
vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
vm_LHR_ApplicationClass.CONTACT_EMAIL = GV_Email;
if (file.ContentLength > 0)
{
string _FileName = FileNamePrefix + Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/Documents/LEAD/DOCS_IN"), _FileName);
file.SaveAs(_path);
}
// TempData["UploadStatus"] = "File(s) Uploaded Successfully!!";
string Style = "display: block";
ViewBag.DDAreaPartialStyle = Style;
//Email
EmailResponder.Email_Response(1, GV_Email, "AppDev@xxxx", "Document Submission Confirmation", "Thank You For Your Submission " + GV_FNAME + " " + GV_LName, ViewBag.UploadStatus);
ViewData["UploadStatus"] = "File(s) Submitted";
//return PartialView("_SFU");
return RedirectToRoute ("ApplicationUpload",vm_LHR_ApplicationClass);
}
catch(Exception e)
{
VM_LHR_ApplicationClass vm_LHR_ApplicationClass = new VM_LHR_ApplicationClass();
vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
vm_LHR_ApplicationClass.CONTACT_FIRST_NAME = GV_LName;
vm_LHR_ApplicationClass.CONTACT_EMAIL = GV_Email;
TempData["UploadStatus"] = "File upload failed!!";
string Style = "display: block";
ViewBag.DDAreaPartialStyle = Style;
return View("ApplicationUpload", vm_LHR_ApplicationClass);
//return PartialView("_SFU");
}
}
//TODO: SEE https://stackoverflow.com/questions/38501116/how-can-i-refresh-just-a-partial-view-in-its-view
[HttpPost]
public ActionResult Upload_DD_Files(IEnumerable<HttpPostedFileBase> FileData)
{
var EmailResponder = new ApplicationClasses.EmailResponderClass();
//MakeUploadDate No Spaces:
string UploadDate = DateTime.Today.ToString("MM/dd/yy");
UploadDate = UploadDate.Replace("/", string.Empty);
foreach (var file in FileData)
{
//MakeUniqueTicker See: https://stackoverflow.com/questions/9278909/net-short-unique-identifier
var ticks = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).Ticks.ToString();
//var ans = DateTime.Now.Ticks - ticks;
//var UniqueId = ans.ToString("x").Remove(4,4);
string FileNamePrefix = UploadDate + "__" + LHRController.GV_LName + LHRController.GV_FNAME + "__" + Guid.NewGuid().ToString().Remove(5, 10);// ticks.Remove(5, 11);
//string filepath = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
string filepath = FileNamePrefix + System.IO.Path.GetExtension(file.FileName);
file.SaveAs(Path.Combine(Server.MapPath("~/Documents/LEAD/DOCS_IN"), filepath));
//There is where code to save to DB would Do
}
//Try To Display Results
string Style = "display: block";
ViewBag.SFSAreaPartialStyle = Style;
ViewBag.UploadStatus = "Selected File(s) Uploaded Successfully";
//Email
EmailResponder.Email_Response(1, GV_Email, "AppDev@xxxx", "Document Submission Confirmation", "Thank You For Your Submission " + GV_FNAME + " " + GV_LName, Convert.ToString(FileData.Count() + " " + ViewBag.UploadStatus));
return View("ApplicationUpload");
//return Json("File{s) Uploaded Successfully");
}
//public ActionResult Upload_DD_Files(IEnumerable<HttpPostedFileBase> FileData, string Info)
//{
// //MakeUploadDate No Spaces:
// string UploadDate = DateTime.Today.ToString("MM/dd/yy");
// UploadDate = UploadDate.Replace("/", string.Empty);
// foreach (var file in FileData)
// {
// //MakeUniqueTicker See: https://stackoverflow.com/questions/9278909/net-short-unique-identifier
// var ticks = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).Ticks.ToString();
// //var ans = DateTime.Now.Ticks - ticks;
// //var UniqueId = ans.ToString("x").Remove(4,4);
// string FileNamePrefix = UploadDate + "__" + LHRController.GV_LName + LHRController.GV_FNAME + "__" + Guid.NewGuid().ToString().Remove(5, 10);// ticks.Remove(5, 11);
// //string filepath = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
// string filepath = FileNamePrefix + System.IO.Path.GetExtension(file.FileName);
// file.SaveAs(Path.Combine(Server.MapPath("~/Documents/LEAD/DOCS_IN"), filepath));
// //There is where code to save to DB would Do
// }
// ViewBag.UploadStatus = "Selected File(s) Uploaded Successfully";
// return View();
//}
//Show UPLOAD Sections
[ChildActionOnly]
public ActionResult DisplayDragAndDropArea()
{
return PartialView("_DUL");
}
[ChildActionOnly]
public ActionResult DisplaySelectedFilesArea()
{
return PartialView("_SFU");
}
//FILE TO DOWNLOAD
//SEE: https://www.codeproject.com/Tips/1028915/How-To-Download-a-File-in-MVC-2
public ActionResult DownloadFile()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "Documents/LEAD/DOCS/";
byte[] fileBytes = System.IO.File.ReadAllBytes(path + "LHR_Application.PDF");
string fileName = "LHR_Application.PDF";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
}
}
Here is the PARENT view:
@model DOT.ViewModels.VM_LHR_ApplicationClass
@Html.AntiForgeryToken()
<style>
ul.no-bullets {
list-style-type: none; /* Remove bullets */
padding: 0; /* Remove padding */
margin: 0; /* Remove margins */
}
</style>
@{
ViewBag.Title = "ApplicationUpload";
}
<br />
<div class="col-sm-6">
<div>
<br />
<br>
<p>
<b>
Please fill out the Contact Information below. Please insure that the information is correct and complete.
This information will be used only for the purpose of linking the uploaded Application with the Support Documentation.<br />
</b>
</p>
<h3 class="glyphicon glyphicon-alert"></h3>
<p>
<b>Please Note:</b>
If returning to upload addtional documents to a claim, please insure that the contact information entered is correct and is the same as the initial upload.
</p>
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<form id="ContactInfoForm" action="/LHR/ApplicationUpload" method="Post">
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
</div>
</div>
<div class="col-sm-6">
<div class="row">
<div class="row text-left col-lg-offset-1">
<label>Contact Information (Required)</label>
</div>
<div class="col-sm-6">
@Html.Editor("CONTACT_FIRST_NAME", new { htmlAttributes = new { @class = "form-control form-control-sm", placeholder = "*First Name", @style = "font-size:12px; width:125px;" } }) @*, @style = " width: 160px;"*@
@Html.ValidationMessage("CONTACT_FIRST_NAME", "", new { @class = "text-danger" })
</div>
<div class="col-sm-6">
@Html.Editor("CONTACT_LAST_NAME", new { htmlAttributes = new { @class = "form-control form-control-sm", placeholder = "*Last Name", @style = "font-size:12px; width:125px;" } })
@Html.ValidationMessage("CONTACT_LAST_NAME", "", new { @class = "text-danger" })
</div>
</div> @* END ROW 1*@
<div class="row" style="margin-top:5px">
<div class="col-sm-12">
@Html.Editor("CONTACT_EMAIL", new { htmlAttributes = new { @class = "form-control form-control-sm", placeholder = "*Email Address", @style = "font-size:12px; width:255px;" } })
@Html.ValidationMessage("CONTACT_EMAIL", "", new { @class = "text-danger" })
<br />
@*<p>
If an Email Address is provide, an email comformation that the application was sent and recieved will be sent.
</p>*@
</div>
</div>
<div>
@*<button type="button" id="btn_DD_Upload" value="Click Here Send Documents" onclick="Display_DD_Area()">Confirm</button>*@
@*onclick="Display_DD_Area()*@
<input type="submit" id="btn_DD_Upload" value="Click Here Send Documents" class="btn btn-success" ) /> @*onclick="Display_DD_Area()" onclick="Display_DD_Area('@TempData["ContactValidationErrors"]' *@
</div>
</div>
</div>
</form>
}
<br />
<div class="col-sm-12" style="@ViewBag.DDAreaPartialStyle" id="UploadInstrNotes">
<div class="row">
@*<div>
<h2>Single File Upload</h2>
@using (Html.BeginForm("SingleFileUpload", "LHR", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
@ViewBag.Message
</div>
}
</div>*@
<h3 class="glyphicon glyphicon-education"></h3>
<p>
<b>How To Instructions</b>
Please use either the Browse Selected File or the Drag and Drop file upload option to upload your documents to .<br />
Both options allow you to send one or multiple files at a time.<br />
</p>
<h3 class="glyphicon glyphicon-alert"></h3>
<p>
<b>Please Note:</b>
It is important before uploading documents that the contact information above is correct and complete.<br /><br />
</p>
<p>
<b>Acceptable File Types are the following:</b>
</p>
<ul class="no-bullets">
<li> <span class="glyphicon glyphicon-file">.PDF</li>
<li><span class="glyphicon glyphicon-file">.TXT</li>
<li><span class="glyphicon glyphicon-file">.JPEG</li>
<li><span class="glyphicon glyphicon-file">.JPG</li>
<li><span class="glyphicon glyphicon-file">.DOC</li>
<li><span class="glyphicon glyphicon-file">.DOCX</li>
<li><span class="glyphicon glyphicon-file">.XLS</li>
<li><span class="glyphicon glyphicon-file">.XLSX</li>
</ul>
</div>
</div>
</div>
<br />
<div class="col-sm-6">
<div class="row">
<div class="col-sm-12">
@*DRAG AND DROP UPLOAD AREA|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*@
<div class="form-horizontal" style="@ViewBag.DDAreaPartialStyle" id="DD_Area">
@{ Html.RenderAction("DisplayDragAndDropArea");}
</div>
@*||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*@
</div>
</div>
<div class="row">
<div class="col-sm-12">
@*DRAG AND DROP UPLOAD AREA|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*@
<div class="form-horizontal" style="@ViewBag.DDAreaPartialStyle" id="SFU_Area">
@{ Html.RenderAction("DisplaySelectedFilesArea");}
</div>
@*||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||*@
</div>
<div class="col-sm-12">
<div class="form-horizontal" style="display:block" id="SelectedFilesStatus">
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
@TempData["UploadStatus"]
</div>
</div>
</div>
</div>
</div>
</div>
@section Scripts
{
@*SEE: https://www.youtube.com/watch?v=TYmR59zwwe0*@
@*Issues: https://github.com/weixiyen/jquery-filedrop/issues/185*@
@*<script type="text/javascript" src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js'></script>*@
@*<script type="text/javascript" src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>*@
<script src="https://code.jquery.com/jquery-migrate-3.0.1.js"></script>
<script src="~/Scripts/jquery.filedrop.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
//Get Validation Error Count To control Display
//See: https://stackoverflow.com/questions/10008023/how-do-i-access-viewbag-from-js
@*var ContactValidationErrors = '@ViewBag.ContactValidationErrors'
var CVE = parseInt(ContactValidationErrors)+1*@
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn_DD_Upload").click(function ()
{
//alert("Test");
debugger;
var FName = document.getElementById("CONTACT_FIRST_NAME").value;
//alert(FName);
var LName = document.getElementById("CONTACT_LAST_NAME").value;
//alert(LName);
var Email = document.getElementById("CONTACT_EMAIL").value;
//alert(Email);
if (FName ==""|| LName == "" || Email == "")
{
DisplayDDAreaOff();
}
else
{
DisplayDDAreaOn();
}
})
});
function DisplayDDAreaOn() {
$('#DD_Area').show();
}
function DisplayDDAreaOff() {
$('#DD_Area').hide();
}
@*var url = '@Url.Action("DisplayDragDropArea")';
debugger;
$('ContactInfoForm').submit(function () {
if (!$(this).valid()) { return false; }*@
function Display_DD_Area(ContactValidationErrors)
{
//alert(ContactValidationErrors)
debugger;
//var CVE = 0;
//var Valid = false;
//alert(parseInt(ContactValidationErrors,10));
var CVE = parseInt(ContactValidationErrors,10);
if (isNaN(CVE))
{
Valid = true;
}
else
{
Valid = false;
}
//alert(CVE);
//alert(Valid);
//alert("I Have Been Clicked Dr. Shagwell, Im Outside The Partial Sir.");
if (!isNaN(CVE))
{
$('#DD_Area').hide();
$('#DD').hide();
$('#UploadInstrNotes').hide();
//$('#DD').load('/shared/_DUL');
}
else if (isNaN(CVE) && Valid == true)
{
$('#DD_Area').show();
$('#DD').show();
$('#UploadInstrNotes').show();
//$('#DD').load('/shared/_DUL');
}
ContactValidationErrors = "";
}
function Open_DD_Area_Page() {
}
</script>
<script type="text/javascript">
$(function ()
{
$('#DropArea').filedrop
({
url: '@Url.Action("Upload_DD_Files")',
allowedfiletypes: ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/doc', 'application/xls', 'application/dtxt'],
allowedfileextensions: ['.doc', '.docx', '.pdf', '.jpg', '.jpeg', '.png', '.gif', '.xls', '.xlsx','txt'],
paramname: 'FileData',
maxfiles: 10,
maxfilesize: 100, //MegaBytes
queuefiles: 2,
dragOver: function ()
{
$('#DropArea').addClass('active-drop');
},
dragLeave: function ()
{
$('#DropArea').removeClass('active-drop');
},
drop: function ()
{
$('#DropArea').removeClass('active-drop');
},
uploadFinished: function (i, file, response, time)
{
$('#UploadList').append('<ol> <span class="glyphicon glyphicon-save"> ' + file.name + '</ol>')
},
afterAll: function (e)
{
$('#DropArea').html('---- File(s) Uploaded Successfully To ----')
}
})
})
</script>
}
Partial View For the Select File Option
@model DOT.ViewModels.VM_LHR_ApplicationClass
@*@using (Ajax.BeginForm("Upload_DD_Files", "LHR", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))*@
@*@using (Html.BeginForm("Upload_DD_Files", "LHR", FormMethod.Post, new { enctype = "multipart/form-data" }))*@
@*Using Ajax Keeps it from posting back and clearning the users contact infomation, there has to be a better way because
using this way pevents alerting the users that the files uploaded*@
@*@using (Ajax.BeginForm("Upload_DD_Files", "LHR", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))*@
@using (Html.BeginForm("Upload_DD_Files", "LHR", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<input type="hidden" name="Info" value='Selected' />
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FileData, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-4">
@Html.TextBoxFor(model => model.FileData, "", new { @type = "file", @multiple = "multiple" })
@Html.ValidationMessageFor(model => model.FileData, "", new { @class = "text-danger" })
</div>
<div class="col-md-offset-1 col-md-3">
<input type="submit" value="Upload Selected File(s)" class="btn btn-primary" />
</div>
<div class="form-horizontal" style="display:block" id="SelectedFilesStatus">
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
@ViewData["UploadStatus"]
</div>
</div>
</div>
</div>
@*<div class="form-group">
<div class="col-md-offset-2 col-md-5">
<input type="submit" value="Upload Selected File(s)" class="btn btn-primary" />
@ViewBag.UploadStatus
</div>
</div>*@
@*<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
@ViewBag.UploadStatus
</div>
</div>*@
</div>
}