File upload using dropzon.js - asp.net-mvc-4

I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.

File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.

Related

Modal Pop-Up Not Closing Properly After Form Submission

This is a follow-up to the following post:
Modal Pop-Up Displaying Incorrectly When ModelState.IsValid = false Redirect
My Pop-Up validates correctly but after it process the form data it is not getting closed. Once the data gets loaded in the db, I run the following:
TempData["ID"] = status.IssueID;
return RedirectToAction("edit");
Since the Modal doesn't close, the view data gets populated in the modal and not the window.
If I try to use return View("edit"); the underlying page fails because there is no model data on the page.
Here is the current code that I implemented from the post referenced above:
<script>
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
});
})
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
Here is the code that I run to open the modal:
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
Add New Status
And here are the actions when I submit data from the modal:
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult CreateEdit(StatusViewModel model)
{
if (ModelState.IsValid)
{
StatusModel status = new StatusModel();
status.IssueID = model.IssueID;
status.StatusDate = DateTime.Today;
status.Status = model.Status;
status.ColorCode = model.ColorCode;
status.NextStep = model.NextStep;
if (model.addedit == "edit")
{
status.UpdatedByNTID = AppHttpContext.Current.Session.GetString("userntid").ToString();
string done = _adoSqlService.UpdateStatus(status);
}
else
{
status.EnteredByNTID = AppHttpContext.Current.Session.GetString("userntid").ToString();
string done = _adoSqlService.InsertStatus(status);
}
TempData["ID"] = status.IssueID;
return RedirectToAction("edit");
}
else
{
return PartialView("_CreateEdit", model);
}
}
Before I implemented the Javascript code as identified in the link, the modal form closed properly but I couldn't validate. After implementation, the modal form validates but the modal receives the redirect instead of closing. What am I doing wrong
the Modal doesn't close, the view data gets populated in the modal and not the window.
It's the expected result, Ajax render the result of redirection to the modal. You should do the redirection in the done function.
Modify the CreateEdit method:
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult CreateEdit(StatusViewModel model)
{
if (ModelState.IsValid)
{
StatusModel status = new StatusModel();
status.IssueID = model.IssueID;
status.StatusDate = DateTime.Today;
status.Status = model.Status;
status.ColorCode = model.ColorCode;
status.NextStep = model.NextStep;
if (model.addedit == "edit")
{
status.UpdatedByNTID = AppHttpContext.Current.Session.GetString("userntid").ToString();
string done = _adoSqlService.UpdateStatus(status);
}
else
{
status.EnteredByNTID = AppHttpContext.Current.Session.GetString("userntid").ToString();
string done = _adoSqlService.InsertStatus(status);
}
TempData["ID"] = status.IssueID;
}
return PartialView("_CreateEdit", model);
}
Add a hidden input in the partial view to mark if the returned model has passed the validation.
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
Then determine whether to redirect in the script:
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
var isValid = $('body').find('[name="IsValid"]').val() == 'True';
if (isValid) {
$('body').find('#modal-container').modal('hide');
window.location.href = "/Issue/Edit";
}
});
})
Result:

Getting data from another page using XMLHttpRequest

Good morning everyone. I tried creating a site that could get information from another page and feed the response into a div tag, but it didnt work. I checked with a very similar one i learnt from. Here is the HTML code.
<html>
<head>
<script>
function checkit(){
var samxml; var username;
if (window.XMLHttpRequest){
samxml = new XMLHttpRequest();}
else {
samxml = new ActiveXObject("Microsoft.XMLHTTP");
}
samxml.onreadystatechange = function() {
if (samxml.readyState == 4 && samxml.status == 200){
document.getElementById("check").innerHTML = samxml.responseText;}
}
username = document.getElementById("username").value;
samxml.open("POST", "check.php",true);
samxml.send( "username" );
}
}
</script>
</head>
<body>
<form>
<label for ="username">User ID:</label>
<input type = "text" name = "username" id = "username"/>
<div id = "check"></div>
<button type = "button" onclick = "checkit()">Check</button>
</form>
</body>
</html>
Here is the PHP page:
//php file
<?php
$user = $_POST["username"];
if ($user == "samuel") {
echo "Hmm. Chosen! Choose another one";}
else {
echo "Nice one";}
?>
Thanks so much.

Banking API queried by Javascript

I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).

Google CSE - multiple search forms on the same page

i'm aiming to put 2 search forms on the same wordpress page. i'm using the iframe form code and have already sorted out how to direct that to a search element.
but the form includes the following script:
www.google.com/cse/brand?form=cse-search-box&lang=en
which starts by defining the search box by ID
var f = document.getElementById('cse-search-box');
but if you use multiple forms then you (incorrectly i know) end up with elements that have the same ID.. and the branding+ focus/blur events don't work across both forms.
the form basically looks like:
<form action="/search.php" class="cse-search-box">
<div>
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="32" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
<script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
if this were a jquery script i think it'd be easy to change the ID to a class name and do an .each() iteration. but google's code is pure javascript and i'm not familiar with that, though
i read getElementbyClass isn't super reliable.
so is this fixable or not worth worrying over?
eventually i commented out that script from google.com and replaced it w/ my own custom version:
`
if (window.history.navigationMode) {
window.history.navigationMode = 'compatible';
}
jQuery.noConflict();
jQuery(document).ready(function($) { //tells WP to recognize the $ variable
//from google's original code- gets the URL of the current page
var v = document.location.toString();
var existingSiteurl = /(?:[?&]siteurl=)([^&#]*)/.exec(v);
if (existingSiteurl) {
v = decodeURI(existingSiteurl[1]);
}
var delimIndex = v.indexOf('://');
if (delimIndex >= 0) {
v = v.substring(delimIndex + '://'.length, v.length);
}
$(".cse-search-box").each( function() {
var q = $(this).find("input[name=q]");
var bg = "#fff url(http:\x2F\x2Fwww.google.com\x2Fcse\x2Fintl\x2Fen\x2Fimages\x2Fgoogle_custom_search_watermark.gif) left no-repeat";
var b = "#fff";
if (q.val()==""){
q.css("background",bg);
} else {
q.css("background",b);
}
q.focus(function() {
$(this).css("background", b);
});
q.blur(function() {
if($(this).val()==""){
$(this).css("background", bg);
}
});
//adds hidden input with site url
hidden = '<input name="siteurl" type="hidden" value="'+ v +'">'
$(this).append(hidden);
});
}); //end document ready functions
`
and on the search.php page that you are directing the results to (so this is a 2-page search form, i found a tutorial on that online somewhere) you will need:
`
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
/**
* Extracts the users query from the URL.
*/
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(
parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
function onLoad() {
// Create a custom search control that uses a CSE restricted to
// code.google.com
var customSearchControl = new google.search.CustomSearchControl)('google_search_id');
var drawOptions = new google.search.DrawOptions();
drawOptions.setAutoComplete(true);
// Draw the control in content div
customSearchControl.draw('results', drawOptions);
// Run a query
customSearchControl.execute(getQuery());
}
google.setOnLoadCallback(onLoad);
`

Struts2 + jQuery Autocompletion

I used the jQuery autocompletion for my Struts2 application.
Pratically, my action made a list of strings that jQuery use. This is the script:
$().ready(function() {
$("#tag").autocomplete("/myAction/Action", {
multiple : true,
autoFill : true,
minChars:1
});
});
During typing appear the box with the suggestions. The problem is that the box render another value,
exactly render the code of my JSP ( links to CSS for the autocomplete plug-in).
How can I solve this?
This is my JSP:
<html>
<head>
<script src="<%=request.getContextPath()%>/scripts/jquery-latest.js"></script>
<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/main.css" type="text/css" />
<link rel="stylesheet" href="<%=request.getContextPath()%>/scripts/jquery.autocomplete.css" type="text/css" />
<script type="text/javascript" src="<%=request.getContextPath()%>scripts/jquery.bgiframe.min.js"></script>
<script type="text/javascript" src="/<%=request.getContextPath()%>/query.dimensions.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery.autocomplete.js"></script>
<script type="text/javascript">
$().ready(function() {
$("#tag").autocomplete("/myAction/Action", {
multiple : true,
autoFill : true,
minChars:1
});
});
</script>
</head>
<body>
<s:form action="Action" theme="simple">
<s:iterator value="elencoMateriali" var="asd">
<s:property value="#asd" escape="false"/>
</s:iterator>
<s:textfield id="tag" name="tagField" label="tag" />
</s:form>
</body>
I think it's too late for an answer, but the probles is still remaining in Struts2. I have made some modifications to solve such problem:
Copy the jquery.struts2.js file into you js path.
Edit the jquery.struts2.js fil and look for 'success: function(data)' in the handle of the Autocompleter Widget, and replace the function for the next one:
success: function(data) {
var x = 0;
if (data[o.list] !== null) {
var isMap = false;
if (!$.isArray(data[o.list])) {
isMap = true;
}
var result = [];
$.each(data[o.list], function(j, val) {
if (isMap) {
result.push({
label: val.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: val,
id: j
});
}
else {
if (o.listkey !== undefined && o.listvalue !== undefined) {
result.push({
label: val[o.listvalue].replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: val[o.listvalue],
id: val[o.listkey]
});
}
else {
result.push({
label: data[o.list][x].replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: data[o.list][x],
id: data[o.list][x]
});
}
}
x++;
});
response(result);
}
}
Now, if you subscribe a onSelectTopics method on your jsp code, you will have a new item.id element available, so you can set the id value into a hidden o whatever you want.
Now, your autocompleter show a list with the strong word, fills the input with the selection, and mantains the id in a variable you can catch.
Remember to add the modified js in the include header section.
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<s:form action="ActionJson" theme="simple">
<s:url id="elencoFuffa" action="ActionJSON"/>
<sx:autocompleter id="autocompleter" name="materiale" loadOnTextChange="true" preload="false" href="%{elencoFuffa}" size="24" loadMinimumCount="1" showDownArrow="false" cssClass="dropDown" onchange="submit();"/>
<s:submit value="Prosegui"/>
<s:property value="luoghiSmaltimento"/>
</s:form>
Now, the Action:
public class Action extends ActionSupport {
private String materiale;
private String luoghi;
private List<String> elencoMateriali;
private Map<String, String> json;
public String execute() throws Exception {
System.out.println("------------------" + materiale);
return SUCCESS;
}
public String getMateriali() throws Exception {
MaterialiDAO dao = new MaterialiDAO();
List<Materiali> toResult = new ArrayList<Materiali>();
toResult = dao.findAll();
elencoMateriali = new ArrayList<String>();
Iterator i = toResult.iterator();
while (i.hasNext()) {
Materiali m = (Materiali) i.next();
elencoMateriali.add(m.getValueNomemateriale());
}
return SUCCESS;
}
public String getJson() throws Exception {
json = new HashMap<String, String>();
if (materiale != null && materiale.length() > 0) {
MaterialiDAO dao = new MaterialiDAO();
List<Materiali> materiali = dao.findByLikeValue(materiale);
for (Materiali m : materiali) {
json.put(m.getValueNomemateriale(), "" + m.getIdMateriali());
}
}
return SUCCESS;
}
public String trovaLuogo() throws Exception {
LuoghismalDAO daoL = new LuoghismalDAO();
MaterialiDAO daoM = new MaterialiDAO();
Materiali m = daoM.findByMaterialiName(materiale);
if (m != null) {
luoghi = m.getLuoghismal().getValueDescrluogo();
return SUCCESS;
} else {
luoghi = "-- Scegliere un materiale --";
return SUCCESS;
}
}
/* Getters and setters */
At the end the struts.xml
<action name="ActionJSON" class="it.action.Action"
method="getJson">
<result type="json">
<param name="root">json</param>
</result>
</action>