I have a ASP.NET/C# application that I am developing. I am using BlueImp File Uploader to try to upload a file to my ASHX handler. Everything is working fine. What the ASHX handler is doing is its storing the image in a SQL Server database.
My problem is, when my handler gets executed, it needs to pass along an ID with it, so it knows what record to store the image in. Right now, my form is all client side/ajax, so there are no postbacks. I'd like to keep it that way, if possible.
Here is the code I'm using to call the handler:
$('#fileupload').fileupload({
url: 'W9UploadHandler.ashx',
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}
});
My ID, right now, is stored in a hidden div. I can access it like so:
var id = $('#divHostApplicationId').text();
How do I pass this ID onto my ASHX handler? I know I could pass it on as a query parameter with the 'url' parameter, but it seems Blueimp doesn't allow you to dynamically change the url. Once its set, it seems to be set forever. Any ideas?
you can use formData:
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var input = $('#divHostApplicationId');
data.formData = {example: input.val()};
if (!data.formData.example) {
input.focus();
return false;
}
});
Related
I'm trying to figure out how to be able to export an iCal file from my calendar. I can't get it to work, it does not start to "download" the file.
Right now I just try to get one meeting, but later on I will make a for loop to get all the meetings in the database to the iCal file, but I just want to check if it works, but it does not.
This below is my method in the controller and later the jQuery to call the method.
[HttpPost]
public ActionResult AddToICalendar()
{
var ctx = new OruBloggenDbContext();
var meetings = ctx.Meetings.FirstOrDefault(u => u.MeetingID == 1);
var icalStringbuilder = new StringBuilder();
icalStringbuilder.AppendLine("BEGIN:VCALENDAR");
icalStringbuilder.AppendLine("PRODID:-//MyTestProject//EN");
icalStringbuilder.AppendLine("VERSION:2.0");
icalStringbuilder.AppendLine("BEGIN:VEVENT");
icalStringbuilder.AppendLine("SUMMARY;LANGUAGE=en-us:" + meetings.MeetingTitle);
icalStringbuilder.AppendLine("CLASS:PUBLIC");
icalStringbuilder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
icalStringbuilder.AppendLine("DESCRIPTION:" + meetings.MeetingDesc);
icalStringbuilder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", meetings.MeetingStartDate));
icalStringbuilder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", meetings.MeetingEndDate));
icalStringbuilder.AppendLine("SEQUENCE:0");
icalStringbuilder.AppendLine("UID:" + Guid.NewGuid());
icalStringbuilder.AppendLine("END:VEVENT");
icalStringbuilder.AppendLine("END:VCALENDAR");
var bytes = Encoding.UTF8.GetBytes(icalStringbuilder.ToString());
return this.File(bytes, "text/calendar", "ical.ics");
}
Javascript:
<script>
$(function () {
$(document)
.on("click", "#icalBtn", function () {
exportiCal();
});
function exportiCal() {
$.ajax({
url: '/MeetingCalendar/AddToICalendar',
type: "POST",
//data: { downloadFileName = "thisEvent.ics" },
success: function (data) {
alert("hejejje");
}
});
}
});
</script>
The reason nothing downloads is because you can't download files via AJAX. Instead of being delivered to a file on your computer's disk, the downloaded content is going into the data variable in your "success" function.
To solve it, instead of using AJAX, make your action method accept GET requests and just user a regular hyperlink to link the user to it:
[HttpGet]
public ActionResult AddToICalendar()
{
//..etc
and
Download to iCalendar
You can remove all your jQuery code.
N.B. Logging that data value to the console (instead of just alerting meaningless junk) - or using your browser's network tools to see what is going on - would have let you see that, and you might have seen the problem sooner...maybe you need to do a bit more debugging in future.
I'm currently writing a MVC C# application. Everything works just fine. I have a bit of functionality, where I fill up a Bootstrap modal box using an Ajax call, but the new page gets cached, despite my efforts to prevent that.
On my main page I have the following actionhandler to fill up the modal box:
function setExtraPermsOrAtts(appID){
$.ajax({
cache:false,
url: "/Group/_modifyAppPermissionsOfGroup?appID=" + appID
}).done(function (result) {
$("#addApplicationBody").html(result);
$('#modal-add-application').modal('show');
});
}
This gets caught by the following method:
public ActionResult _modifyAppPermissionsOfGroup(int? appID = 0)
{
if (appID != 0)
{
ViewBag.selectedAppID = appID;
Session["selectedGroupAppID"] = appID;
ViewBag.modifyPermsLater = true;
}
Group group = (Group)Session["currentGroup"];
return View(group);
}
Another thing that might be relevant is the point where it 'goes wrong'. The resulting View in the Modalbox, has a few radio buttons, depending on the content of the database. There I do a razor statement to get the DB value:
bool valueOfRadButtons = BusinessLogic.Domain.GroupIS.getExistingGroupPermission(
Model.LoginGroupID, myItem.ApplicationPermissionID).LoginPermissionState;
Does anyone know where I'm going wrong? Is it the Ajax call? The ActionResult method in the Controller? Or the inline razor statement? I know the data gets saved properly, cause I see so in the DB
You can specify that the response shouldn't be cached like this:
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
It can be more easy if you make your own attribute and decorate the action with it as shown here.
I currently have the following code within my server side API:
// Enable both Get and Post so that our jquery call can send data, and get a status
[System.Web.Mvc.HttpGet]
[System.Web.Mvc.HttpPost]
public HttpResponseMessage Upload()
{
// Get a reference to the file that our jQuery sent. Even with multiple files, they will all be their own request and be the 0 index
HttpPostedFile file = HttpContext.Current.Request.Files[0];
// do something with the file in this space
// {....}
// end of file doing
// Now we need to wire up a response so that the calling script understands what happened
HttpContext.Current.Response.ContentType = "text/plain";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = new { name = file.FileName };
HttpContext.Current.Response.Write(serializer.Serialize(result));
HttpContext.Current.Response.StatusCode = 200;
// For compatibility with IE's "done" event we need to return a result as well as setting the context.response
return new HttpResponseMessage(HttpStatusCode.OK);
}
I use the following jQuery to call it:
$(function () {
$('#fileupload').fileupload({
dataType: "json",
url: "/api/Upload",
limitConcurrentUploads: 1,
sequentialUploads: true,
progressInterval: 100,
maxChunkSize: 10000,
add: function (e, data) {
$('#filelistholder').removeClass('hide');
data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
$('</div><div class="progress"><div class="bar" style="width:0%"></div></div>').appendTo(data.context);
$('#btnUploadAll').click(function () {
data.submit();
});
},
done: function (e, data) {
data.context.text(data.files[0].name + '... Completed');
$('</div><div class="progress"><div class="bar" style="width:100%"></div></div>').appendTo(data.context);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#overallbar').css('width', progress + '%');
},
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.bar').css('width', progress + '%');
}
});
});
The problem I am having is, I don't understand where I can grab the completed uploaded file. As when I add a breakpoint this one function get's called 100's of times on one image upload.
Could someone please give me help on why it's called so much?
And I suppose the best way to ensure that it is only been an image uploaded (no exe, viruses etc).
I just want to upload the file, confirm it's an image, resize the file and save to by database as a Base64 string or to the file system either or?
Thanks!
I'm trying to make a booking system for Orchard by using the jQuery FullCalendar (Link to the jQuery FullCalendar).
I found this youtube tutorial on how to install FullCalendar as a Widget in Orchard and got it setup in 1.7.2 after a while.
Now I would like to be able to add and edit events from the site (currently it's setup so you have to add new events through the admin panel, same with editting).
I think the place where I have to start could be in this pastebin.
When I use the following code:
//dayClick: function(date, allDay, jsEvent, view) {
// if (allDay) {
// alert('Clicked on the entire day: ' + date);
// }else{
// alert('Clicked on the slot: ' + date);
// }
// alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
// alert('Current view: ' + view.name);
//},
And then click on a time on my calendar it tells me the date and so on (so the onclick event works), I'm just not sure how I should move on from that.
I would like to be able to just add an event from the calendar view atm. So far I have been able to add it, but not to save it to the database, I suppose it has something to do with:
var fullCalEvents = [];
var iterator = function (event) {
var newEvent;
newEvent = new Booking.Event(event.title, event.start, event.end, event.url, false);
fullCalEvents.push(newEvent);
};
But I'm not sure where to start.
The current select I have written is the one where I can add an event, but not save it in the database.
I can provide more information if need be!
I hope someone can enlighten me on how to do this.
Thank you
Casper
Lets give a try LeCattez,
I do not mess around with C# for a while, but you might know what i'm going to talk about.
In your handler class you will need to have something like this, this is from another question here in SO.
<%# WebHandler Language="C#" Class="MyHandler" %>
using System;
using System.Web;
public class MyHandler : IHttpHandler
{
public void ProcessRequest (HttpContext ctx)
{
var json = new JSONResonse()
{
Success = ctx.Request.QueryString["name"] != null,
Name = ctx.Request.QueryString["name"]
};
ctx.Response.ContentType = "application/json";
ctx.Response.Write(JsonConvert.SerialzeObject(json));
}
public bool IsReusable {
get { return false; }
}
}
In your handler you must fetch data sent from AJAX call. This is an example on how you can send data with Jquery.Ajax.
select: function(start, end, allDay, jsEvent, view){
$.ajax({
type: 'POST',
url: ajaxcallURL(_url,"2001"),
data: {"start":start,"end":end,"allDay":allDay }, //Here you can send data to server
beforeSend:function(){
//TODO do somethin before sendind data
},
complete:function(){
calendar.fullCalendar( 'refetchEvents' ); //This line will force hte calendar to re-get all eventSources
//wich means everytime you select a time period in calendar this will happen
},
success: function(data)
{
//TODO Do stuff with eventual data you need to send back to client
},
error: function(jqXHR, textStatus, errorThrown){
//Handle errors here
}
});
},//SELECT
Offcourse you can send to server an object, example an JSON object and fetch that object there like the example you see above.
No in the http Handler you will have to save to DB data.
Did you understood? Or you need further explanation? Let me know...
I currently have this working but it requires me to have a static method as the method called in the code behind. I would like to be able to access some member variables that can't be static. I'm not married to the Javascript implementation and am open to other suggestions that would help me achieve this.
If there is other information that would be helpful let me know and I can include.
EDIT: Let me clarify, I'm looking to edit a value in one of the user controls on the page based on the button click. I am holding the user controls in a list on the page and using the parameters passed through the javascript to find the user control that I want to update and modify the value there.
It currently looks like this:
Javascript:
function incrementCompletes(obj)
{
var firstParameter = $(obj).parents('.parentClass1').find('.childClass1').html();
var secondParameter = $(obj).parents('.parentClass2').find('.childClass2').html();
var parameters = "{'firstParam':'" + firstParameter+ "','secondParam':'" + secondParameter+ "'}";
$.ajax({
type: "POST",
url: "Page.aspx/StaticMethod",
contentType: "application/json; charset=utf-8",
data: parameters,
dataType: "json",
success:
function DoOtherStuffHere(result) {
var x = $(obj).parents('.classWithStuffToChange');
var y = $(x).find('.otherClassWithStuffToChange');
y[0].innerHTML=" + " + result.d;
}
});
}
Code behind:
[WebMethod]
public static int StaticMethod(string parameter1, string parameter2)
{
//Do some stuff
//Return a value
}
I would like to find a solution that does not require the method called to be static.
If you want to access member varaibles of the page, there has to be an instance of the page class. That means that you have to do a postback instead of calling a web method.
Use a regular Button control, that will cause a postback and you can use it's Click event to run a method in the code behind. If you don't want the page to be reloaded, you can use ASP.NET AJAX to do the callback using AJAX.