Asp.Net Core - Not Able to Upload Files From Dropzone JS - asp.net-core

I am using asp.net core 2.2 with dropzone js.
I am trying to submit a form along with the files contained in dropzone js.
I have an input file field (can be hidden or not hidden). I want to assign dropzone files to this field and submit it. But the Forms field is always null.
Here is the code:
MVC Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(ViewModels.Photo model)
{
var files = HttpContext.Request.Form.Files; // this is also empty
....
}
MVC Model:
public class Photo
{
...
public List<IFormFile> Files { get; set; }
}
HTML:
<form asp-action="Add" asp-controller="Photos" method="post" id="addForm" enctype="multipart/form-data">
<div class="dropzone">
<input asp-for="Files" type="file" multiple hidden/>
</div>
<button type="submit">Submit</button>
</form>
JS:
var e = "#addForm",
var t = new Dropzone(e, {
maxFilesize: 1,
acceptedFiles: ".png,.jpg,.jpeg",
uploadMultiple: false,
autoProcessQueue: false
});
t.on("addedfile", function (o) {
$("#Files").files = t.files;
})

You might use a different method signature of the action
[HttpPost]
public ActionResult Add(HttpPostedFileBase file)
{
//handle file.InputStream
}
This example shows uploading the files one by one: https://gillesleblanc.wordpress.com/2017/01/25/integrating-dropzone-js-into-an-asp-net-mvc-site/

I managed to get things working and it was a minor fix.
I changed below code
$("#Files").files = t.files;
to
$("#Files").files = t.hiddenFileInput.files;
t.files is an array of files being captured by dropzone where as t.hiddenFileInput.files is an FileList object of files being captured by dropzone.
The $("#Files").files is also an FileList object that's why t.files was not working due to type mismatch.
Now it submits form fields along with files with default submit mechanism.

Related

Uploading asp.net core 3.1 Razor

I'm trying to upload files in ASP.NET core 3.1, but in my Post I'm not receiving the file.
That count = 0 is what I always get.
#cshtml
<input asp-for="app.FormFile" id="input-2" name="input2[]" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
#cshtml.cs
public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
var filePath = Path.GetTempFileName();
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
}
}
// Process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size });
}
In ASP.NET core 2.0 this worked fine! What's wrong?
The param name is files, but you're explicitly setting the input name to input2[], so they don't match up. ASP.NET Core isn't going to try to interpret that you've uploaded some files so you probably want them to go on this param. If it can't find something to bind the data to (by name), it's just going to discard it and move on.
The name should files so it matches up to the param name: name="files".
even if I pass the name it still came with count = 0 <input asp-for="Laudos.FormFile" id="files" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
You can try to specify an encoding type (enctype) of multipart/form-data for your <form> tag, like below.
<form method="post" enctype="multipart/form-data">
<input asp-for="Laudos.FormFile" id="input-2" name="files" type="file" class="file" multiple data-show-upload="true" data-show-caption="true">
<input type="submit">
</form>
Test Result

In Asp.Net Core, how can I get the multipart/form-data from the body?

In Asp.Net Core, it appears that they have done away with the Request.Content.ReadAsMultipartAsync functionality in favor of the IFormFile.
This makes uploading where you have an actual file a LOT easier, however, I have a use case where I need to upload a file to browser memory, process it, then send it as part of the multi-form data in the body. IFormFile cannot see this as there is no actual file to read. It only works if you have a filename property on the Content-Disposition and an actual file on the client to upload.
In my Asp.Net 4 app, I could read the mutlipart data in the body whether that was sent between boundaries or as an attached file.
How do I accomplish this in .Net Core?
What I figured out is that the multipart values are passed into the HttpRequest.Form as an array of key/value pairs. The "name" value on the body's multipart determines the name of the key.
I created a helper method that grabs both files and form values.
public static List<FileModel> GetFileModelsFromRequest(HttpRequest request)
{
var fileModels = new FileModels();
foreach (var formField in request.Form)
{
// Form data
var fileModelText = formField.Value;
... process and add to the FileModel list
}
if (request.Form.Files != null && request.Form.Files.Count > 0)
{
foreach (var file in request.Form.Files)
{
using (MemoryStream ms = new MemoryStream())
{
// File data
formFile.CopyTo(ms);
}
... process and add to the FileModel list
}
}
return fileModels;
}
I have done it this way. when I had to capture image from webcam and process (show that image in browser) it in browser memory and later on post that image using a form.
public IActionResult Index()
{
var files = HttpContext.Request.Form.Files;
if (files != null)
{
foreach (var file in files)
{
var fileName = file.Name;
}
}
return View();
}
I used a JS library Webcam.js to capture image from webcam and show that image on the same page. and once a user is satisfied with the image, s/he can upload the image to the server.
<!-- Configure settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach('#camera');
</script>
<!-- handle snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.getElementById('imageResults').innerHTML =
'<img src="' +
data_uri +
'"/>';
Webcam.upload(data_uri,
'/Default/Index',
function (code, text) {
console.log('Photo Captured');
});
});
}
</script>
<div class="panel panel-default">
<div class="panel-heading">Camera</div>
<div class="panel-body">
<div id="camera"></div>
<!-- A button for taking snaps -->
<form>
<input type="button" class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div class="panel panel-default">
<div class="panel-heading">Captured Image</div>
<div class="panel-body">
<div id="imageResults">captured image will appear here...</div>
</div>
<br />
<br />
</div>
let me know if this is what you are looking for.

kendo editor not responding after multiple requests to the same page in IE

I have a very weird bug. I have a page on MVC that displays two editors and gets passed a model with the value for both editors. The model is as follows:
public class BulletinsModel
{
[AllowHtml]
[Display(Name = "Some Bulletin")]
public string SomeBulletin { get; set; }
[AllowHtml]
[Display(Name = "Other Bulletin")]
public string OtherBulletin { get; set; }
}
I then, defined a view which receives this view model and maps it to two kendo editors.There is also some javascript code to make a post to update the information.
#model BulletinsModel
<div id="settings">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.SomeBulletin, new { #class = "col-md-6 text-left" })
#(Html.Kendo().EditorFor(m => m.SomeBulletin).Encode(false).Name("Some_Bulletin"))
#Html.LabelFor(m => m.OtherBulletin, new { #class = "col-md-6 text-left" })
#(Html.Kendo().EditorFor(m => m.OtherBulletin).Encode(false).Name("Other_Bulletin"))
</div>
</div>
</div>
My code for my action method that renders this view is as follows (nothing fancy):
[HttpGet]
public PartialViewResult Index()
{
ViewBag.ActiveSectionName = "Bulletins";
var bulletinModel = GetBulletinsModel();
return PartialView("_Bulletins",bulletinModel);
}
However, my issue is that after hitting the Index action a couple of times, the editors become non responsive and I cannot edit the information on them. This only happens on IE, as I have not been able to replicate the issue in other browsers.
EDIT: I have just noticed that the editor is frozen. In order to be able to edit what's inside of the editor I need to click on any option of the toolbar to make it responsive once again. Why is that?
Turns out that the issue is happening with IE as detailed in this post:
Adding, removing, adding editor -> all editors on page become read only in IE. The problem is with the iframes inside the editor. I was loading my page with an Ajax request to which I had to add the following code before making the request to make it work.
function unloadEditor($editor) {
if ($editor.length > 0) {
$editor.data('kendoEditor').wrapper.find("iframe").remove();
$editor.data('kendoEditor').destroy();
}
}
unloadEditor($('#myEditor'));

Passing textbox value from View to action without using Html.begin form and Submit button

I have created a texbox. When user give some input in the textbox and click the actionlink below, the value of the textbox will get pass to the actionResult(FWMenu) in the controller. I can not use html.begin form and submit button in the view. And i can not even use [httppost] in my controller.
Is it possible in that way? If yes then please help me how.
I have not used any class in model.
Below is my Controller.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult FWMenu(string username)
{
return View();
}
}
This is my View.
<div>
#Html.TextBox("txtUserName")
#Html.ActionLink("Login", "FWMenu", new { username = #Html.TextBox("txtUserName") })
</div>
You need to use javascript/jquery to build the url and redirect. From your comments you mentioned you wanted to use a image rather than a button or link, and that you will have multiple items, so assuming you html is
<div>
<input type="text" name="username">
<img class="submit scr=....>
<div>
<script>
var urlBase='#Url.Action("FWMenu");
$('.submit').click(function() {
var userName = $(this).prev('input').val();
location.href = urlBase + '/' + userName;
}
</script>
Side note: No real point using #Html.TextBox("txtUserName") and if you have multiple instance of this it would generate invalid html (duplicate id attributes) and in any case the name of the parameter is username so it would have needed to be #Html.TextBox("username")`

unobtrusive validation not working with dynamic content

I'm having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.
I've been spending days trying to get this code to work with no luck.
Here's the View:
#model MvcApplication2.Models.test
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<div id="res"></div>
<input id="submit" type="submit" value="submit" />
}
The Partial View:
#model MvcApplication2.Models.test
#Html.TextAreaFor(m => m.MyProperty);
#Html.ValidationMessageFor(m => m.MyProperty);
<script type="text/javascript" >
$.validator.unobtrusive.parse(document);
</script>
The Model:
public class test
{
[Required(ErrorMessage= "required field")]
public int MyProperty { get; set; }
}
The Controller:
public ActionResult GetView()
{
return PartialView("Test");
}
and finally, the javascript:
$(doument).ready(function () {
$.ajax({
url: '/test/getview',
success: function (res) {
$("#res").html(res);
$.validator.unobtrusive.parse($("#res"));
}
});
$("#submit").click(function () {
if ($("form").valid()) {
alert('valid');
return true;
} else {
alert('not valid');
return false;
}
});
The validation does not work. Even if I don't fill any information in the texbox, the submit event shows the alert ('valid').
However, if instead of loading dynamically the view, I use #Html.Partial("test", Model) to render the partial View in the main View (and I don't do the AJAX call), then the validation works just fine.
This is probably because if I load the content dynamically, the controls don't exist in the DOM yet. But I do a call to $.validator.unobtrusive.parse($("#res")); which should be enough to let the validator about the newly loaded controls...
Can anyone help ?
If you try to parse a form that is already parsed it won't update
What you could do when you add dynamic element to the form is either
You could remove the form's validation and re validate it like this:
var form = $(formSelector)
.removeData("validator") /* added by the raw jquery.validate plugin */
.removeData("unobtrusiveValidation"); /* added by the jquery unobtrusive plugin*/
$.validator.unobtrusive.parse(form);
Access the form's unobtrusiveValidation data using the jquery data method:
$(form).data('unobtrusiveValidation')
then access the rules collection and add the new elements attributes (which is somewhat complicated).
You can also check out this article on Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC for a plugin used for adding dynamic elements to a form. This plugin uses the 2nd solution.
As an addition to Nadeem Khedr's answer....
If you've loaded a form in to your DOM dynamically and then call
jQuery.validator.unobtrusive.parse(form);
(with the extra bits mentioned) and are then going to submit that form using ajax remember to call
$(form).valid()
which returns true or false (and runs the actual validation) before you submit your form.
Surprisingly, when I viewed this question, the official ASP.NET docs still did not have any info about the unobtrusive parse() method or how to use it with dynamic content. I took the liberty of creating an issue at the docs repo (referencing #Nadeem's original answer) and submitting a pull request to fix it. This information is now visible in the client side validation section of the model validation topic.
add this to your _Layout.cshtml
$(function () {
//parsing the unobtrusive attributes when we get content via ajax
$(document).ajaxComplete(function () {
$.validator.unobtrusive.parse(document);
});
});
test this:
if ($.validator.unobtrusive != undefined) {
$.validator.unobtrusive.parse("form");
}
I got struck in the same problem and nothing worked except this:
$(document).ready(function () {
rebindvalidators();
});
function rebindvalidators() {
var $form = $("#id-of-form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}
and add
// Check if the form is valid
var $form = $(this.form);
if (!$form.valid())
return;
where you are trying to save the form.
I was saving the form through Ajax call.
Hope this will help someone.
just copy this code again in end of modal code
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
;)