ASP.NET MVC view with dropzone hangs on the server - asp.net-mvc

I am using ASP.NET MVC to develop my application.
My view is been supported by Dropzone library written in Javascript.
FUNCTION: upload one or multiple files to the controller. It returns an object to the same view with the uploaded file(s), so the user can label each uploaded file with the type of file.
ISSUE: after testing, my conclusion is that the configuration and use of Dropzone.js in my view (see below) for some reason hangs the execution of the application. What I mean, is that the code under the if {} condition in the view is not being rendered.
It looks to me, like the page in the server is never refreshed when the controller calls the cshtml page. So it always produces the same output result, under all conditions.
If I use the code <input type="file" name="files" multiple/> then the app it will work.
CSHTML markup:
<div class="col ml-2">
<table id="UploadedDataTable" border="1" class="blueTable display nowrap" style="width:100%">
<thead>
<tr>
<th scope="col" style="text-align:center" width="65%" title="Uploaded file name">Uplodaded file name</th>
<th style="text-align:center" title="Uploaded file type">Document Type</th>
</tr>
</thead>
<tbody>
#if (Model.UploadedFiles != null && Model.UploadedFiles.Attachments.Count > 0)
{
for (int i = 0; i < Model.UploadedFiles.Attachments.Count; i++)
{
<tr>
<td>#Model.UploadedFiles.Attachments[i].Name</td>
#if (string.IsNullOrEmpty(Model.UploadedFiles.Attachments[i].DocumentType))
{
Model.UploadedFiles.Attachments[i].DocumentType = ISAA.Business.Models.Invoices.InvoicesParameters.getInstance().GetDocumentType()[0].Code;
<td>Doc. Type: #Html.DropDownListFor(m => Model.UploadedFiles.Attachments[i].DocumentType, new SelectList(ISAA.Business.Models.Invoices.InvoicesParameters.getInstance().GetDocumentType(), "Code", "Name"), " - Select Document Type -", new { #class = "form-control form-control-sm", aria_describedby = "shipment-entry-19" })</td>
}
else
{
<td>Doc. Type: #Html.DropDownListFor(m => Model.UploadedFiles.Attachments[i].DocumentType, new SelectList(ISAA.Business.Models.Invoices.InvoicesParameters.getInstance().GetDocumentType(), "Code", "Name"), " - Select Document Type -", new { #class = "form-control form-control-sm", aria_describedby = "shipment-entry-19" })</td>
}
</tr>
}
}
</tbody>
</table>
<small>Define correctly the Document Type</small>
</div>
Javascript (dropzone configuration):
#section scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/dropzone")
<script type="text/javascript">
$(document).ready(function () {
Dropzone.autoDiscover = false;
$('#myDropzone').dropzone({
//parameter name value
paramName: "files",
//clickable div id
clickable: '#previews',
//preview files container Id
previewsContainer: "#previewFiles",
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
// url:"/", // url here to save file
maxFilesize: 100,//max file size in MB,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".cvs,.xls,.xlsx,.pdf",// use this to restrict file type
init: function () {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function (file) {
console.log('new file added ', file);
$('.dz-success-mark').hide();
$('.dz-error-mark').hide();
});
// Send file starts
self.on("sending", function (file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function (progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
// On removing file
self.on("removedfile", function (file) {
console.log(file);
});
$('#Submit').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
// Validate form here if needed
if (self.getQueuedFiles().length > 0) {
self.processQueue();
} else {
self.uploadFiles([]);
$('#myDropzone').submit();
}
});
self.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
}
});
})
</script>
}

Related

List<IFormFile> files gets nothing from dropzone post mvc

I'm trying to send images from dropzone to my controller mvc project by httpPost
The forms are calling correctly the IActionResult but the files count are always 0
When the forms load I get
but I'm already giving a URL. Don't know what's the error.
Here is my cshtml script of dropzone config
#section Scripts
{
<link rel="stylesheet" href="~/css/basic.css" />
<link rel="stylesheet" href="~/css/dropzone.css" />
<script type="text/javascript" src="~/js/dropzone.js"></script>
<script type="text/javascript" src="~/js/dropzone-amd-module.js"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
$('#myDropzone').dropzone({
url:"/Aprovacoes/SaveUploadedFile",
method: "post",
//parameter name value
paramName: function () { "files" },
//clickable div id
clickable: '#previews',
//preview files container Id
previewsContainer: "#previews",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
// url:"/", // url here to save file
maxFilesize: 100,//max file size in MB,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.pdf",// use this to restrict file type
init: function () {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function (file) {
console.log('new file added ', file);
$('.dz-success-mark').hide();
$('.dz-error-mark').hide();
});
// Send file starts
self.on("sending", function (file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function (progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function (progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function (file) {
console.log(file);
});
$('#Submit').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
// Validate form here if needed
if (self.getQueuedFiles().length > 0) {
self.processQueue();
} else {
self.uploadFiles([]);
$('#myDropzone').submit();
}
});
self.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
}
});
})
</script>
And here is the form
#using (Html.BeginForm("SaveUploadedFile", "Aprovacoes", FormMethod.Post, new { #name = "myDropzone", id = "myDropzone", #enctype = "multipart/form-data" }))
{
<br />
<div>
<div id="previews" class="dz-default dz-message box__input dropzone">
<div style="text-align:center">
<i class="fa fa-cloud-upload" style="font-size:23px;position:relative;top:4px;"></i> <span style="margin-left:20px">Drop files to attach or browse</span>
</div>
</div>
</div>
<br />
<div>
<input type="submit" id="Submit" name="Submit" class="btn btn-success m-t-5" value="Submit" />
</div>
}
My controller httpPost method
[HttpPost]
public IActionResult SaveUploadedFile(List<IFormFile> files)
{
//do stuff
}
always come 0
This is my working solution:
View Part
#using (Ajax.BeginForm("YourAction", "YourController", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm", #enctype = "multipart/form-data" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="col-md-12 dropzone">
<div class="dropzone-previews" id="dropzonePreview">
<i class="icon-file-upload icon-5x absolute-center text-muted"></i>
</div>
</div>
</div>
<div class="row form-group mt-3">
<div class="col-md-12">
<input class="btn btn-inverse btn-primary" id="btnSubmit" name="inputSubmit" type="submit" value="Save" />
</div>
</div>
</div>
</div>
}
Script Part
Dropzone.autoDiscover = false;
var options = {
paramName: "PhotoFiles",
addRemoveLinks: true,
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
thumbnailWidth: 250,
thumbnailHeight: 250,
dictRemoveFile: 'Delete',
previewsContainer: '#dropzonePreview',
clickable: '.dropzone',
acceptedFiles: ".jpeg,.jpg,.png",
};
var dropZone = new Dropzone("form#ajaxForm", options);
dropZone.element.querySelector("input[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// if dropzone has file process them, if not send empty array
if (dropZone.getQueuedFiles().length > 0) {
dropZone.processQueue();
} else {
$("#ajaxForm").submit();
}
});
dropZone.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
OnSuccess(response);
});
dropZone.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
OnFailure(response);
});
Controller Part
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult InsertPhotos()
{
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
//process files
}
}
//return some result
return Json(result, JsonRequestBehavior.AllowGet);
}
Hope it helps.

Pass Object Parameter from javascript\ajax to function in Controller

I have a table that i want to be able to update the status of each line that checkbox is on
(see attached screenshot)
The checkbox propery in the Model is Not Mapped to the database ([NotMapped])
Html:
<div class="row">
<div class="col-12 text-right">
<button class="btn btn-primary" onclick="ApproveStatus()">Approve Checked Lines</button>
</div>
</div>
javaScript:
#section Scripts{
<script type="text/javascript">
function ApproveStatus() {
var pdata = new FormData();
swal({
title: "Are you sure?",
text: "Once Updated, you will not be able to Undo this",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: "PaymentHistory/ApproveStatus",
type: "POST",
data: pdata,
processData: false,
contentType: false,
success: function (data) {
swal("Success!", {
icon: "success",
});
}
});
setTimeout(function () {
location.reload()
}, 100);
} else {
swal("Nothing Changed!");
}
});
}
</script>
}
And in the Controller i have the function (haven't written the logic yet)
[HttpPost]
public IActionResult ApproveStatus()
{
}
table in html:
<table id="tblData" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>Address</th>
<th>Payment Type</th>
<th>Amount</th>
<th>Payment Date</th>
<th>Status</th>
<th></th>
</thead>
#foreach (PaymentHistory paymentHistory in Model)
{
<tr>
<td>#ViewBag.getPaymentAddress(paymentHistory.SentFromAddressId).ToString()</td> <td>#ViewBag.getPaymentType(paymentHistory.SentFromAddressId).ToString()</td>
<td>#paymentHistory.Amount$</td>
<td>#paymentHistory.PayDate</td>
<td>#paymentHistory.Status</td>
#if (paymentHistory.Status != "Approved")
{
<td>
<div class="text-center">
<input type="checkbox" asp-for="#paymentHistory.isChecked"/>
</div>
</td>
}
else
{
<td></td>
}
</tr>
}
</table>
My only issue is that i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter,
Any ideas how can i do this?
Thank you
i want to pass the Object from the View (that contains the lines and status of the checkbox) to the function in the controller as a parameter, Any ideas how can i do this?
To achieve your requirement, you can try to add a hidden field for SentFromAddressId field, like below.
<td>
<div class="text-center">
<input type="hidden" asp-for="#paymentHistory.SentFromAddressId" />
<input type="checkbox" asp-for="#paymentHistory.isChecked" />
</div>
</td>
then you can get the sentFromAddressId of each checked row and populate it in form data object.
var pdata = new FormData();
$("input[name='paymentHistory.isChecked']:checked").each(function (index, el) {
var sentFromAddressId = $(this).siblings("input[type='hidden']").val();
pdata.append("Ids", sentFromAddressId);
})
and post the data to action method with following code snippet.
$.ajax({
type: 'POST',
url: '/PaymentHistory/ApproveStatus',
data: pdata,
processData: false,
contentType: false,
datatype: 'json',
success: function (res) {
//...
}
});
ApproveStatus action method
public IActionResult ApproveStatus(int[] Ids)
{
//code logic here
//update corresponding record based on id within Ids
Get all checked checkboxes id in an array, use that array to update table

checkbox value always showing null value in mvc

I am always getting null value through checkbox in mvc. If the checkbox is checked or uncheck it contain null value only.
Here is my code,
View Page
#model IEnumerable<SchoolWebApplication.Models.EventMaster>
<table id="tblEvent" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px; display:none">Event Id</th>
<th style="width:150px">Event</th>
<th style="width:150px">Active</th>
</tr>
#if(Model != null)
{
foreach (SchoolWebApplication.Models.EventMaster eventMaster in Model)
{
<tr>
<td class="EventID" style="display:none">
<span>#eventMaster.EventID</span>
</td>
<td class="Event">
<span style="color:darkgreen">#eventMaster.Event</span>
<input type="text" value="#eventMaster.Event" style="display:none; color:darkgreen" />
</td>
<td class="IsActive">
<span style="color:darkgreen">#eventMaster.IsActive</span>
#if (#eventMaster.IsActive == true)
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" checked="checked" name="abc"/>
}
else
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" name="abc"/>
}
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</td>
</tr>
}
}
</table>
<script type="text/javascript">
function AppendRow(row, EventID, Event, IsActive) {
//Bind EventID.
$(".EventID", row).find("span").html(EventID);
//Bind Event.
$(".Event", row).find("span").html(Event);
$(".Event", row).find("input").val(Event);
//Bind IsActive.
$(".IsActive", row).find("span").html(IsActive);
$(".IsActive", row).find("input").val(IsActive);
$("#tblEvent").append(row);
};
//Edit event handler.
$("body").on("click", "#tblEvent .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblEvent .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
$(this).hide();
var event = {};
event.EventID = row.find(".EventID").find("span").html();
event.Event = row.find(".Event").find("span").html();
event.IsActive = row.find(".IsActive").find("span").html();
$.ajax({
type: "POST",
url: "/Event/Update",
data: JSON.stringify({ eventMaster: event }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.IsActive);
}
});
});
</script>
Controller
try
{
EventMaster updatedEvent = (from c in entities.eventMaster
where c.EventID == eventMaster.EventID
select c).FirstOrDefault();
updatedEvent.Event = eventMaster.Event;
updatedEvent.IsActive = eventMaster.IsActive;
entities.SaveChanges();
return new EmptyResult();
}
catch (Exception ex)
{
return View();
}
Now, in table there is a three field EventID, Event and Active. In active there is a checkbox containing at update time.
Now, the issue is coming that if the checkbox is check or not check it is containing null value only.
So thats why at the fetch time it showing uncheck only.
Thank You.
Asking for the .val of a checkbox will get you the contents (if any) of the value attribute on the input element - this will not change when the user checks the box.
To check if a checkbox is checked in jQuery you should use something like:
if (input.is(":checked")){}
At the moment, you're storing the current value of .IsActive in the span and the value of the checkbox, and then when the update method runs, just grabbing that same value and putting it into the span - resulting in not updating anything.
Looking further at your code though - you should confirm what your method is actually posting back to the server - looking at it you are passing raw HTML into some parameters on the object:
event.IsActive = row.find(".IsActive").find("span").html();
At best, event.IsActive will be the string "True" (or False), rather than an actual boolean that your model is expecting. You would be better off changing that line to something like:
event.IsActive = row.find(".IsActive").find("input").is(":checked");
And then confirm what is being sent to the server in the network tab of your browser.

How to let user know the resume they are submitting is too large

my cshtml file for upload, where would the javacsript go in this file?
#{
ViewBag.Title = "Upload";
}
<div id="progressbar">
<div id="progressbar" class="all-rounded" style="width: 20%"><span></span></div>
</div>
<div class="jumbotron">
<h2>Job Application Management System</h2>
<p class="lead2"> Welcome #((string)(ViewData["FullName"])), Please upload your resume here. Thank you!</p>
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td> <label> </label> <input type="file" class="btn btn-default" name="File" id="File" /></td>
</tr>
<tr>
<td><input type="submit" class="btn btn-default" id="upload" value="Upload" /></td>
</tr>
</table>
if (TempData["notice"] != null)
{
<p>#TempData["notice"]</p>
<p><button class="btn btn-default" onclick="location.href='#Url.Action("Create", "Accomplishments")';return false;">Continue To Accomplishments</button></p>
}
}
Here is my working code that shows how to accept a resume and save it using asp.net mvc
How do I post an error message stating that the file size is too large if the user submits a file that cannot be handled. Right now, if a user submits a file too large, it takes them to an errors page. I just want a popup or something on the screen that tells them to submit a file that is smaller. Thanks!
if (resume.File.ContentLength > 0)
{
string fileName = Path.GetFileName(resume.File.FileName);
string path = Path.Combine(Server.MapPath("~/Content/Resumes"), fileName);
resume.File.SaveAs(path);
}
TempData["notice"] = "Resume Added: "+ resume.File.FileName;
return View(resume);
}
catch (Exception)
{
ViewBag.Message = "Upload Error";
return View("Upload");
}
}
You can do this with simple javascript :
<script type="text/javascript">
$('#image-file').on('change', function() {
var filesize = this.files[0].size/1024/1024).toFixed(2) + " MB");
//Now can use use filesize variable and check it's value and show pop.
});
</script>
OR you can use this :
function GetFileSize(fileid) {
try {
var fileSize = 0;
//for IE
if ($.browser.msie) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //It will calculate file size in kb
// Put Your Alert or Validation Message Here
}
}
catch (e) {
alert("Error is :" + e);
}
}
Or you can check file size on form submit as:
<script type="text/javascript">
$(document).ready(function(){
$('#upload').on('click', function(e) {
e.PreventDefault();
var filesize = $("#File").files[0].size/1024/1024).toFixed(2)); //filesie in MB
//Now can use use filesize variable and check it's value and show pop.
if(parseInt(filesize)>3){ alert("File too large");return false; }
else{ $("form").submit(); }
});
});
</script>

ASP.NET Mvc two dependent dropdownlist?

script
<script type="text/javascript">
$(document).ready(function () {
$('musteri_sno').change(function () {
$('form_sayac_secimi').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
}
});
}
return false;
});
});
});
</script>
html
#using (Html.BeginForm("SayacSecimiPartial", "SayacOkumalari", FormMethod.Post, new { id = "form_sayac_secimi" }))
{
<table>
<tr>
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
<td>
<input type="submit" value="Uygula" />
#Html.Hidden("sno", new { sno = ViewData["sno"] })
</td>
</tr>
</table>
}
I want to fill second dropdown with values that is returned from first one.How can I do this?
Thanks.
In the success callback of your ajax call, build the option tag filled with the values you are returned and then append it to the select tag named "sayac_no".
success: function(result) {
var opt = '';
for (var i = 0; i < result; i++) {
opt += '<option value="' + result[i].value + '">' + result[i].name + '</option>';
}
$('select[name=sayac_no]').html(opt);
}
I suppose the result object is a list of objects with two properties, name and value.
Modify it accordingly to your needs and improve it because this is just a very basic version.

Resources