How to pass file content into [WebMethod] with jquery uploadify plugin - asp.net

I would like to pass file content into [WebMethod] with jquery uploadfy plugin
But the Upload method can not be invoked.Can anyone help me out? Thanks in advance!
Index.aspx:
<head runat="server">
<title></title>
<link href="uplodify/uploadify.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="uplodify/swfobject.js" type="text/javascript"></script>
<script src="uplodify/jquery.uploadify.v2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '/uplodify/uploadify.swf',
'script': '/Index.aspx/Upload',
'cancelImg': '/uplodify/cancel.png',
'buttonImg': '/uplodify/browse.jpg',
'sizeLimit': 262144,
'fileExt': '*.jpg',
'fileDesc': '*.jpg',
'folder': '/pic',
'onProgress': function (event, ID, fileObj, data) {
var bytes = Math.round(data.bytesLoaded / 1024);
$('#' + $(event.target).attr('id') + ID).find('.percentage').text(' - ' + bytes + 'KB ');
return false;
},
'onSelect': function (event, ID, fileObj) {
if (parseInt(fileObj.size) > 262144) {
window.alert fileObj.name");
return false;
}
},
'onComplete': fun
});
});
function checkImport() {
if ($.trim($('#file_uploadQueue').html()) == "") {
alert('please select pic!');
return false;
}
else {
jQuery('#file_upload').uploadifyUpload();
return true;
}
}
function fun(event, queueID, fileObj, response, data) {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img height="100" width="100" src="nopic.jpg" id="filesUploaded" runat="server" />
<input id="file_upload" name="file_upload" type="file" />
<input id="Button1" type="button" value="uploadfile" onclick="checkImport()" runat="server"
class="ui-corner-all" /><br />
</div>
</form>
</body>
Index.cs:
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Upload(byte[] FileData)
{
return "";
}
}

In ASP.NET Page methods expect to be invoked using application/json content type. So you could use either a new WebForm or a generic handler to handle the file upload:
$(document).ready(function () {
$('#file_upload').uploadify({
'swf': '<%= ResolveUrl("~/uploadify/uploadify.swf") %>',
'uploader': '<%= ResolveUrl("~/upload.ashx") %>'
});
});
and the generic handler might look like this:
public class Upload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile uploadedFile = context.Request.Files["FileData"];
// TODO: do something with the uploaded file. For example
// you could access its contents using uploadedFile.InputStream
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get { return true; }
}
}
Also to facilitate debugging use a tool such as Fiddler as it allows you to inspect the HTTP traffic between the client and the web server, showing you potential errors you might have. Also a javascript debugging tool such as FireBug or Chrome developer tools is a must-have.

Related

Why is my parameter null when I try to pass object using MS AJAX PageMethods

I tried the following snippet as well:
PageMethods.MyMethod(JSON.stringify(person), OnMyMethodComplete);
Client markup:
</form>
<script type="text/javascript">
var person = { firsName: "World" };
function test() {
PageMethods.MyMethod(person, OnMyMethodComplete);
}
function OnMyMethodComplete(result) { alert(result); }
window.onload = function () {
test();
};
</script>
</body>
</html>
Code-behind:
[WebMethod]
public static string MyMethod(Person p)
{
return "Hello " + p.FirstName;
}
Debug:
I was defining var Person in client code, but looking for var p on the server-side.

Photo Upload in ASP.NET

I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {
var FileFolder = $('#hdnPhotoFolder').val();
var fileToUpload = getNameFromPath($('#uplPhoto').val());
var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
alert(filename);
if (checkFileExtension(fileToUpload)) {
var flag = true;
var counter = $('#hdnCountPhotos').val();
if (filename != "" && filename != null && FileFolder != "0") {
//Check duplicate file entry
for (var i = 1; i <= counter; i++) {
var hdnPhotoId = "#hdnPhotoId_" + i;
if ($(hdnPhotoId).length > 0) {
var mFileName = "#Image1_" + i;
if ($(mFileName).html() == filename) {
flag = false;
break;
}
}
}
if (flag == true) {
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxComplete(function () {
$(this).hide();
return false;
});
$.ajaxFileUpload({
url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
secureuri: false,
fileElementId: 'uplPhoto',
dataType: 'json',
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
$('#hdnFullPhotoPath').val(data.upfile);
$('#uplPhoto').val("");
$('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
}
}
},
error: function (data, status, e) {
alert(e);
}
});
}
else {
alert('The photo ' + filename + ' already exists');
return false;
}
}
}
else {
alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
}
return false;
}
PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
<asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
<asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click" OnClientClick="return ajaxPhotoUpload();"/>
</td>
</tr>
</table>
SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Image1.ImageUrl = hdnFullPhotoPath.Value
End Sub
I’d recommend that you drop client side AJAX upload via JS and stick to standard way of uploading. You can probably achieve the same effects without the excessive javascript.
If file type filtering is an issue you can check this post for more details.
Getting extension of the file in FileUpload Control
In either way you have to make a postback so it doesn’t really matter if you upload from JS or the server side except that second method is less complex.
Adding update panel will make this more user friendly and you should be all done.
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="button" id="uploadFile" value="Upload File" />(jpg|jpeg|png|gif)
<div id="uploadStatus" style="color: Red">
</div>
</div>
<script type="text/javascript" language="javascript">
new AjaxUpload('#uploadFile', {
action: 'Handler1.ashx',
name: 'upload',
onComplete: function (file, response) {
if (response == '0') {
$('#uploadStatus').html("File can not be upload.");
}
else {
$('#img').attr("src", "response.path");
}
},
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|png|gif)$/i.test(ext))) {
$('#uploadStatus').html("Invalid File Format..");
return false;
}
$('#uploadStatus').html("Uploading...");
}
});
</script>
Then create a handler for uploading image on server
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string a = "1";
if (context.Request.Files != null && context.Request.Files.Count > 0)
{
if (context.Request.Files[0].ContentLength > 1000)
{
a = "0";
}
}
else
{
a = "0";
}
context.Response.Write(a);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);

asp.net Usercontrol + control value always returns true

I am trying to build a simple animated 'on' & 'off' switch control with an underlying checkbox to store the state whenever the 'switch block' shifts left and right (On and Off), when I import to control to the page which I need to use, the value I get is always True, please advice what am I doing wrong. Thanks.:
ASCX:
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"> </script>
</head>
<body>
<div class="switchcontainer">
<div id="on">On</div>
<div id="off">Off</div>
<div class="block"></div>
</div>
<asp:CheckBox ID="chkSwitch" runat="server" Style="display:none"/>
<script>
$(".block").click(function () {
var $button = $(".block");
if ($button.data("lastMove") == "+=46") {
$('#<%= chkSwitch.ClientID %>').removeAttr('checked'); // --> change check state
$button.animate({
left: '-=46'
});
$button.data("lastMove", '-=46');
} else {
$('#<%= chkSwitch.ClientID %>').attr('checked', 'checked'); // --> change check state
$button.animate({
left: '+=46'
});
$button.data("lastMove", '+=46');
}
});
</script>
</body>
</html>
ASCX.CS
public partial class BoolSwitch : System.Web.UI.UserControl
{
public bool On
{
get { return chkSwitch.Checked; }
}
}
Some page using the usercontrol:
<%# Register TagPrefix="BoolSwitch" TagName="BoolSwitch" Src="/UserControls/BoolSwitch.ascx" %>
<BoolSwitch:BoolSwitch runat="server" ID="boolSwitch_1" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
var x = boolSwitch_1.On; // --> This value is always true;
}

Unable to send message to group in SignalR

I am using SignalR library. I am running 3 instances of my application and then I add two users to a group named 'Test'. Now when i send message to 'Test' group, the message is not delivered at all.
public class ChatHub : Hub
{
public void send(string name, string message)
{
//This line of code is not working
Clients.Group("test").broadcastMessage(message);
//This is working
//Clients.All.broadcastMessage(name, message);
}
public void JoinGroup(string groupName)
{
Groups.Add(this.Context.ConnectionId, groupName);
}
public void RemoveGroup(string groupName)
{
Groups.Remove(this.Context.ConnectionId, groupName);
}
}
//Client side
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="groupName" />
<input type="button" id="joinGroup" value="Join" />
<br />
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="Scripts/j`enter code here`query.signalR-1.0.0-rc1.js"></script>
<script type="text/javascript" src="/signalr/hubs"></script>
</body>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
$('#joinGroup').click(function () {
// Call the Send method on the hub.
chat.server.joinGroup($('#groupName').val());
});
});
});
</script>
</html>
Actually the 'broadcastMessage' on the client was expecting two parameter and i was passing only one parameter while calling 'broadcastMessage' using group.
Changing
'Clients.Group("test").broadcastMessage(message);'
to
'Clients.Group("test").broadcastMessage(name, message);' worked.

How to populate asp:LinkButton from Json data response

first of all apologies for my english.
I'm a newby in json area.
My problem is that i can't parse the data recived in a json response into a asp:LinkButton or whatever asp:element, coz i can't create a correct sintax.
Especifically, What I'm trying to do, is this:
<script type="text/javascript">
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", min_year:"1941", max_year:"2012"}, function (data) {
var makes = data.Makes;
for (var i = 0; i < makes.length; i++) {
($("<asp:LinkButton ID=\"lb" + i +"\" runat=\"server\" />").text(makes[i].make_display )).appendTo("#lbProva");
}
});
<script>
<ul id="lbProva" class="lb_prova" >
</ul>
I hope that someone could help me coz i've tryed many possibilities but no one was the right one.
Thank u in advance.
You can't create asp.net server controls in javascript on client side. If you want to use json data on client side, you must apply it to already generated html controls.
Actually, you can create server controls only on a server. So the question is how to pass AJAX call response to server and enforce it to refresh desired area on a page.
First variant
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var makes = $.map(data.Makes, function (make) { return make.make_display; }).join(";");
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = makes;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
<asp:UpdatePanel runat="server" ID="CarMakersUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField runat="server" ID="CarMakersHiddenField" />
<asp:BulletedList runat="server" ID="MakersList" DisplayMode="LinkButton">
</asp:BulletedList>
</ContentTemplate>
</asp:UpdatePanel>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
foreach (var maker in CarMakersHiddenField.Value.Split(';'))
{
MakersList.Items.Add(maker);
}
}
Second approach is more siutable if you need to pass to server some complex object like array of makers objects. In that case you can serialize this object to JSON string on client and deserialize it on server. Looks like previous version with bit changes:
<script type="text/javascript">
$(function () {
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", { cmd: "getMakes", year: "2009" },
function (data) {
//The 'data' variable contains all response data.
var serializedString = Sys.Serialization.JavaScriptSerializer.serialize(data.Makes);
document.getElementById("<%= CarMakersHiddenField.ClientID %>").value = serializedString;
__doPostBack("<%= CarMakersUpdatePanel.ClientID %>", "");
});
});
</script>
Markup left the same as in the first version.
Server code:
[Serializable]
public class Make
{
public string make_id;
public string make_display;
public bool make_is_common;
public string make_country;
}
protected void Page_Load(object sender, EventArgs e)
{
MakersList.Items.Clear();
if (!String.IsNullOrEmpty(CarMakersHiddenField.Value))
{
var serializer = new DataContractJsonSerializer(typeof(Make[]));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(CarMakersHiddenField.Value)))
{
var makes = serializer.ReadObject(stream) as Make[];
if (makes != null)
{
foreach (var maker in makes)
{
MakersList.Items.Add(new ListItem(maker.make_display, maker.make_id));
}
}
}
}
}

Resources