I am using plupload flash runtime in my website to upload the files as Attachments and send them via email. The website runs fine on chrome, IE9 and IE11 but not on IE8. And most of my users are going to be using IE8. I have been trying many different things but none seemed to be working. Can anyone please suggest me any solution?
This is my javascript code where I am uploading of file takes place.
modules.compose = (function () {
"use strict";
var config = {
id: '',
requestToken: $('meta[name="__AntiForgeryToken"]').attr('content'),
runtimes: 'gears,flash,silverlight,browserplus,html5',
maxFileSize: '200mb',
maxQueueSize: 10485760,
chunkSize: '1mb',
pingFrequency: 100000,
isUploaderOpen: false
},
bindUploader = function () {
$("#uploader").pluploadQueue({
// General settings
runtimes: config.runtimes,
url: '/upload.ashx' + '?id=' + config.id,
max_file_size: config.maxFileSize,
chunk_size: config.chunkSize,
unique_names: false,
headers: { '__AntiForgeryToken': config.requestToken },
// Browse filters
filters: [
{ title: "All files", extensions: "*.*" },
{ title: "Image files", extensions: "jpg,gif,png,tiff" },
{ title: "XML files", extensions: "xml" },
{ title: "PDF documents", extensions: "pdf" },
{ title: "Zip files", extensions: "zip" },
{ title: "Text files", extensions: "txt,log" },
{ title: "Powerpoint documents", extensions: "ppt,pptx,pptm,potx,potm,ppam,ppsx,ppsm,sldx,sldm,thmx" },
{ title: "Excel documents", extensions: "xls,xlsx,xlsm,xltx,xltm,xlsb,xlam" },
{ title: "Word documents", extensions: "doc,docx,docm,dotx,dotm" },
],
preinit: {
Init: function (up, info) {
$('.plupload_header, .plupload_start').remove();
}
},
init: {
UploadProgress: function (up, file) {
bumpProgress(up, file);
},
StateChanged: function (up) {
if (up.total && up.files && up.total.uploaded === up.files.length) {
var parent = $('#upload-status').parent();
$('#upload-status').fadeOut('slow').remove();
$('#send-status').appendTo(parent).fadeIn('slow');
__doPostBack('ctl00$Content$btnSendMessage', '');
}
},
FilesAdded: function (up, files) {
var i = 0;
while (i++ < up.files.length) {
$('#btnSendMessage').removeAttr("disabled");
var ii = i;
while (ii < up.files.length) {
if (up.files[i - 1].name == up.files[ii].name) {
up.removeFile(up.files[ii]);
} else {
ii++;
}
}
}
},
QueueChanged: function (up) {
if (up.total.size > config.maxQueueSize) {
$('#upload-warning-modal').modal('show');
if (up.total.queued - 1 >= 0) {
up.removeFile(up.files[up.total.queued - 1]);
}
}
}
},
// Flash settings
flash_swf_url: '/assets/js/plupload/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url: '/assets/js/plupload/plupload.silverlight.xap'
});
},
bindAddAttachments = function () {
$('#btnAddAttachments').click(function (e) {
e.preventDefault();
if (!config.isUploaderOpen) {
bindUploader();
$('#uploader').show();
config.isUploaderOpen = true;
}
$(this).attr('disabled', 'disabled');
});
},
bindSendMessage = function () {
$('#btnSendMessage').click(function (e) {
e.preventDefault();
if (!Page_ClientValidate()) {
return;
}
$('.plupload_filelist_footer').css('display', 'none');
$('#uploader').block({
message: $('#upload-status'),
css: {
padding: 0,
margin: 0,
width: '50%',
top: '50%',
left: '35%',
textAlign: 'left',
color: '#000',
border: '0',
backgroundColor: 'transparent',
cursor: 'wait'
}
});
$('input[type="text"], textarea').prop('readonly', true).addClass('disabled');
$('#btnSendMessage').button('loading');
var queue = $("#uploader").pluploadQueue();
if (queue) {
queue.start();
} else {
__doPostBack('ctl00$Content$btnSendMessage', '');
}
});
},
bumpProgress = function (up, file) {
if (up.total.percent >= 80) {
$('#upload-status .progress').removeClass('progress-info').addClass('progress-success');
}
$('#upload-status .progress .bar').css('width', up.total.percent + '%');
},
bindTextareaLimit = function () {
$('#txtMessage').limit('2000', '#charsLeft');
},
initAttachmentsButton = function () {
$('#btnAddAttachments').prop('disabled', '');
},
initPing = function () {
(function ping() {
$.get("/ping.ashx");
setTimeout(ping, config.pingFrequency);
})();
};
return {
init: function (options) {
config = $.extend({}, config, options || {});
$(function () {
initAttachmentsButton();
initPing();
bindSendMessage();
bindAddAttachments();
bindTextareaLimit();
});
},
validateRecipientEmail: function (sender, args) {
var proxy = new ServiceProxy('/Default.aspx/', { async: false });
proxy.invoke(
'IsValidRecipient',
{ recipient: $('#txtRecipient').val() },
function (result) {
return (args.IsValid = result.d);
});
},
validateSenderEmail: function (sender, args) {
var proxy = new ServiceProxy('/Default.aspx/', { async: false });
proxy.invoke(
'IsValidSender',
{ sender: $('#txtSender').val() },
function (result) {
return (args.IsValid = result.d);
});
}
};
} ());
Hope I'm not too late. Recently had the same problem. The problem is that you use
headers: { '__AntiForgeryToken': config.requestToken },
But by the specification it is not supported in HTML4 runtime:
http://www.plupload.com/docs/Options#runtimes
headers
A way to pass custom HTTP headers with each upload request. The option is simple set of key/value pairs of header names and their values.
Not supported by html4 runtime.
Requires special operational mode in case of flash and silverlight runtimes.
Since in IE8 can be disabled all other ways to upload files it will use HTML4 runtime, which doesn't have any legal way how to set antiForgery token. So your server-side will think that your sended file is not secure due it doesn't have antiForgery token and with drop with Forbidden HTTP status.
Conclusion - you are not abble to use AntiForgery token with plupload in IE8 in the how it is built in ASP.NET MVC.
Related
I am working in asp.net project with VueJs. I would like to create own message box depends on modal. My problem is to with each $emit call create component, show message box and in hideModal function destroy component.
Actually, when I will call many times in for loop this.$root.$emit('show-message', this.showMessage); - component shows just one time. I want to show every messageBox, not only the first one.
(function() {
'use strict'
Vue.component('message-box', {
props: {},
data: function() {
return {
messageTitle: '',
messageBody: '',
visible: false,
}
},
template: `<b-modal centered v-model="visible">
<template slot="modal-header">
{{messageTitle}}
</template>
<div class="d-block text-center">
{{messageBody}}
</div>
<template slot="modal-footer">
<b-button class="mt-3" variant="outline-info" block v-on:click="hideModal()">Ok</b-button>
</template>
</b-modal>`,
created: function() {
this.$root.$on('show-message', this.showMessage)
},
beforeDestroy: function() {
EventBus.$off('show-message', this.showMessage)
},
methods: {
showModal() {
this.visible = true
},
hideModal() {
this.visible = false
},
close: function(index) {
this.alerts.splice(index, 1)
},
showMessage: function(title, message) {
this.messageTitle = title
this.messageBody = message
this.showModal()
},
},
})
})()
Admittedly, this is not exactly the solution I was looking for. Still, it solves my problem.
(function () {
'use strict';
Vue.component('message-box', {
props: {
},
data: function () {
return {
messages: [],
actualMessage: {},
visible: false
};
},
template:
`<b-modal centered v-model="visible">
<template slot="modal-header" v-if="actualMessage">
{{actualMessage.messageTitle}}
</template>
<div class="d-block text-center" v-if="actualMessage">
{{actualMessage.messageBody}}
</div>
<template slot="modal-footer">
<b-button class="mt-3" variant="outline-info" block v-on:click="hideModal()">Ok</b-button>
</template>
</b-modal>`,
created: function () {
this.$root.$on('show-message', this.showMessage);
},
beforeDestroy: function () {
EventBus.$off('show-message', this.showMessage);
},
methods: {
showModal() {
this.actualMessage = this.messages[0];
this.visible = true;
},
hideModal() {
this.visible = false;
this.messages.splice(0, 1);
if (this.messages.length > 0) {
var vm = this;
setTimeout(function () { vm.showModal(); }, 500);
}
},
showMessage: function (title, message) {
this.messages.push({ messageTitle: title, messageBody: message });
if (!this.visible)
this.showModal();
}
}
});
})();
// this is from local it is json object
{
"Id": 654321,
"Name": "Mohd",
"Age": 22
},
{
"Id": 102030,
"Name": "Fahd",
"Age": 18
}
// this is my code not working
var app = new Vue({
el: '#app',
data: {
socialId: '',
person: ''
},
watch: {
socialId: function() {
this.person = ''
if (this.socialId.length == 6) {
this.lookupsocialId()
}
}
},
methods: {
lookupsocialId: _.debounce(function() {
var app = this
app.person = "Searching..."
axios.get('http://localhost:49999/api/people/' + app.socialId)
.then(function (response) {
app.person = response.data.Name + ', ' + response.data.Age
})
.catch(function (error) {
app.person = "Invalid Zipcode"
})
}, 500)
}
})
but I used this is working perfectly
json object {
"country": "US",
"state": "NY",
"city": "SCHENECTADY"
}
var app = new Vue({
el: '#app',
data: {
socialId: '',
person: ''
},
watch: {
socialId: function() {
this.person = ''
if (this.socialId.length == 5) {
this.lookupsocialId()
}
}
},
methods: {
lookupsocialId: _.debounce(function() {
var app = this
app.person = "Searching..."
axios.get('http://ziptasticapi.com/' + app.socialId)
.then(function (response) {
app.person = response.data.city
})
.catch(function (error) {
app.person = "Invalid Zipcode"
})
}, 500)
}
})
Why when I used it locally not working
you need result to json in file, after you using axio response.json(), you can try the following code
<script>
export default{
data(){
return{
title:"Form Register",
formdata:{},
message:"",
success:0,
}
},
methods:{
register(){
this.axios.post("http://localhost:8888/form-register",this.formdata).then((response) => {
console.log(response);
if(response.data.success>0){
this.message="You register success";
this.success=response.data.success;
}
else{
this.message="Register to failed";
this.success=response.data.success;
}
});
},
}
}
</script>
//construct json
[
{
name:"abc"
age:34
},
{
name:"abc"
age:34
}
]
if use php, you can echo json_encode() in php
I have a stored procedure that equates and gets the occupancy rate of a room. I want to fetch the data from the back-end using JSon and display the output data of the stored procedure in the front-end code. But the output data only sticks at the Business Layer. How can i call it from my Controller using Json?
Here is my code
In my Controller
public JsonResult GetoccupancyRate()
{
string _connectionString = rAppSetting.ConnectionString;
try
{
IList<Hotel> _currentOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now, _connectionString);
IList<Hotel> _yesterdayOccupancyRateList = rHotelFacade.GetOccupancyRate(HotelIDCookie, DateTime.Now.AddDays(-1), _connectionString);
return Json(new
{
success = true,
message = "Success",
yesterdayOccupancyRate = _yesterdayOccupancyRateList,
currentOccupancyRate = _currentOccupancyRateList
},JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new
{
success = false,
message = ex.Message,
currentOccupancyRate = "",
yesterdayOccuoancyRate = ""
}, JsonRequestBehavior.AllowGet);
}
}
Javascript
myapp.factory("occupancyRateService", ['$http', function ($http) {
this.LoadOccupancyRate = function () {
return $http.get("/Dashboard/GetOccupancyRate", {});
};
return this;}]);
myapp.controller('MainController', ['$scope', 'dashboardService', 'occupancyRateService', function ($scope, dashboardService, occupancyRateService) {
$scope.myChart = {
type: 'google.charts.Bar',
options: {},
data: {}
};
$scope.loadOccupancyRateDetails = function () {
occupancyRateService.LoadOccupancyRate().success(function (result) {
if (result.success)
{
var currentOccupancyRateData = result.currentOccupancyRate;
var yesterdayOccupancyRateData = result.yesterdayOccupancyRate;
console.log(result.currentOccupancyRate);
console.log(result.yesterdayOccupancyRate);
//console.log(yesterdayResultData)
if (currentOccupancyRateData || yesterdayOccupancyRateData === null)
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', 0],
['Today', 0]
]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.######%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
else
{
google.charts.load('current', { 'packages': ['line', 'bar'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Day', 'Rate'],
['Yesterday', currentOccupancyRateData],
['Today', yesterdayOccupancyRateData]
]);
//function drawChart() {
// var data = google.visualization.arrayToDataTable([ORData]);
var options = {
chart: {
//title:'Occupancy Rate',
},
bars: 'vertical',
hAxis: { format: 'none', gridlines: { count: 5 } },
vAxis: { format: '.################%' },
height: 180,
//width: 100%,
colors: ['#1b9e77']
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$(window).resize(function () {
drawChart();
});
}
}
})
.error(function (error) {
alert(error);
})
};
$scope.loadOccupancyRateDetails();
//<--------------------------------------->
}]);
I'm making a Select2 call from an MVC view using the following code:
ajax: {
url: url,
delay: 150,
data: function (params) {
return GMK_Select2QueryData(params, 30, additionalData);
},
processResults: function (data, params) {
var resultsArr = [];
for (var i = 0; i < data.items.length; i++) {
resultsArr.push({
id: data.items[i].id,
text: data.items[i].text,
description: data.items[i].description,
data: data.items[i].data
});
}
return {
results: resultsArr,
pagination: {
more: data.more
}
};
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
},
cache: false
}
I'm attempting to capture whether a session has timed out, then return the status code to the "error" function so that I can pop something up on the screen stating they need to log back in. Right now, I'm simply alerting to the screen for testing purposes.
I'm using a Web API ActionFilterAttribute, but when I create an error response, the jqXHR is always status = 0 no matter what I do.
public class SessionActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (ctx.Session == null || ctx.Session["user"] == null)
{
filterContext.Response = filterContext.Request.CreateErrorResponse(HttpStatusCode.RequestTimeout, "Session Timeout");
}
base.OnActionExecuting(filterContext);
}
}
SessionActionFilter Action filter is perfect. No problem in filter
Please update Select2 call as follows:-
Answer 1:-
ajax: {
url: url,
delay: 150,
data: function (params) {
return GMK_Select2QueryData(params, 30, additionalData);
},
processResults: function (data, params) {
var resultsArr = [];
for (var i = 0; i < data.items.length; i++) {
resultsArr.push({
id: data.items[i].id,
text: data.items[i].text,
description: data.items[i].description,
data: data.items[i].data
});
}
return {
results: resultsArr,
pagination: {
more: data.more
}
};
},
params: {
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
}
},
cache: false
}
Can get error in following ways
Using the transport option will cause select2 to break if you just want to handle response errors like in the example below.
transport: {
return $.ajax().error(function() {
alert("error fetching data");
});
}
There is another, much simpler way to handle errors. That is by using the params option like the example below.
params: {
error: function(response) {
alert("error fetching data");
}
}
Hope it helps.
Please reference select2
Another Answer
In Select2.js file add extension of "error"
serach for text "$.extend(params"
Then update extension by following code
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
if (requestNumber < requestSequence) {
return;
}
// TODO - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
},
/* BEGIN added code */
error: function (jqXHR, status, error) {
if (requestNumber < requestSequence) {
return;
}
var r = null;
if (options.error) {
r = options.error(jqXHR, status, error);
}
query.callback(r || { results: [] });
} /* END added code */
});
And your updated ajax call
ajax: {
url: url,
delay: 150,
data: function (params) {
return GMK_Select2QueryData(params, 30, additionalData);
},
processResults: function (data, params) {
var resultsArr = [];
for (var i = 0; i < data.items.length; i++) {
resultsArr.push({
id: data.items[i].id,
text: data.items[i].text,
description: data.items[i].description,
data: data.items[i].data
});
}
return {
results: resultsArr,
pagination: {
more: data.more
}
};
},
error: function (jqXHR, status, error) {
alert(error + ": " + jqXHR.responseText + ": " + jqXHR.status);
},
cache: false
}
hiii to all, i am using jqgrid, and want to display error message if the user wants to delete the truck record which is in use, i have to display a error message truck in use..
here is my jqgrid:-
jQuery(document).ready(function () {
var grid = jQuery("#TrucksGrid141");
grid.jqGrid({
url: '/Admin/GetTrucksForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/SaveTruck',
height: '100%',
pager: '#pagerTrucks',
colNames: ['Id', 'Name', ''],
colModel: [
{ name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Name', index: 'Name', align: "center", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Delete', index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }
],
width: '490',
caption: 'Company Trucks',
hidegrid: false,
delete: true,
cellEdit: true,
viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted != 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
//grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
}
}
}
}
);
grid.jqGrid('navGrid', '#pagerTrucks',
{ resize: false, add: false,search:false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pagerTrucks',
{ title: "Add New Truck", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewTruckModal, position: "First", caption: "" });
});
function showNewTruckModal() {
var grid = jQuery("#TrucksGrid141");
$("#formAddNewTruck").dialog(
{
open: function (event, ui) {
$("#txtName").val('');
$("#trFormErrorTrucks").hide();
$("#trFormErrorTrucks td").text('');
},
buttons: {
"Submit": function () {
debugger;
if (ValidateUsers() == true) {
$('#error').ajaxError(function (event, request, settings) {
$('#waiting').hide();
$(this).addClass('errordiv').text(request.statusText + "" + request.status);
});
$.post('/Admin/AddNewTruck/',
$('#formAddNewTruck').serialize(),
function (data) {
debugger;
if (data == 'Success') {
$('#formAddNewTruck').dialog("close");
grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
else {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(data);
}
});
}
},
"Cancel": function () {
$('#error').removeClass("errordiv").text("");
$('#waiting').hide();
$(this).dialog("close");
}
},
modal: true,
title: "New Truck",
minWidth: 400,
resizable: false
}
).dialog('open');
}
function ValidateUsers() {
var flag = true;
var errorMSG = '';
$("#trFormErrorTrucks td").text('');
if ($("#txtName").val() == '') {
errorMSG += 'Truck Name cannot be blank';
flag = false;
}
if (flag == false) {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(errorMSG);
}
else {
$("#trFormErrorTrucks td").text('');
$("#trFormErrorTrucks").hide();
}
return flag;
}
function deleteRow(rowid) {
jQuery("#TrucksGrid141").delGridRow(rowid, { url: '/Admin/TruckDelete', caption: 'Delete User?', msg: 'Delete selected User? <br />Careful, this is irreversable!', resize: false,success:abc });
}
function emptyText(rowid, cellname, value, iRow, iCol) {
if (cellname == 'Password')
return "";
}
function abc(data)
{
debugger;
}
and here is my cs code from controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TruckDelete(int Id)
{
var error = "";
bool result=true;
DataContext db = new DataContext();
Truck udelete= db.Trucks.Where(el => el.Id == Id).FirstOrDefault();
if (udelete != null)
{
JobSites_ForSnow snow = db.JobSites_ForSnow.Where(el => el.TruckId == Id).FirstOrDefault();
JobSite normal = db.JobSites.Where(el => el.TruckId == Id).FirstOrDefault();
if(snow==null && normal==null)
{
db.Trucks.Remove(udelete);
db.SaveChanges();
}
else
{
error = "Truck in use!";
result= false;
}
}
else
{
error = "Record Not Found!";
result= false;
}
return Json(result,error);
}
can anybody tell me how can i display the error message? i have seen this answer (jqgrid error message on delete) but didn't understood what to do :(. if the question is not clear to you, please let me know by comment, i will explain ...thanks in advance :)
You use currently
return Json(result,error);
as the last line of TruckDelete action, where result have boolean type and error is a string. So the Controller.Json Method (Object, String) where error will be interpreted as contentType of HTTP response. It's your first problem. You should use probably something like
return Json(new Object[] {result, error});
(see here). In the case the method will generate JSON response like
[true,""]
or
[false,"Record Not Found!"]
The client side (jqGrid) can process the response inside of afterSubmit callback. You need just replace unknown (for jqGrid) option success of delGridRow to the following
jQuery("#TrucksGrid141").delGridRow(rowid, {
url: '/Admin/TruckDelete',
caption: 'Delete User?',
msg: 'Delete selected User? <br />Careful, this is irreversable!',
resize: false,
afterSubmit: function (jqXHR) {
return $.parseJSON(jqXHR.responseText); // return decoded response
}
});