Ajax connection with asp.net codebehind and runtime compilation trouble - asp.net

I'm having trouble getting an AJAX call to work, The fail error is the common 404 which means that the call cant find the file/function i wish to call. The problem is even when i use an absolute path in the call it still 404's on me. I can physically inspect the file on the server and even using the same path access an image or .txt file in the same directory through the web.
$.ajax({
type: "post",
url: "http://10.xx.xx.xx/Scripts/Core.aspx.vb/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"selCourse":"'+crsName+'"}',
success: function(result) {
ProcessServerLsnList(result.d);
},
error: function (xhr, status, error) {
AjaxErrorAlert(error);
}
});
As i'm forced to code this from Dreamweaver as a run time compiled codebehind.(Don't ask...) Is there something simple i'm missing that i should check, be it in the asp or iis config on the server or the web.config.
default.aspx Header
<%# Page Language="vb" AutoEventWireup="true" Src="Scripts/Core.aspx.vb" Inherits="CoreFunctionality"%>
<!DOCTYPE>
<html>
<head runat="server">
Core.aspx.vb
Imports System.IO
Imports System.Web.Services.WebService
public partial Class CoreFunctionality
Inherits System.Web.UI.Page
Public Function GetData(ByVal strData As String) As String
return String.Format("It's blank Jim.", strData )
End Function
End Class
background Info on what i need to implement: User clicks on an item it performs multiple javascript actions then without refreshing, the page retrieves data from the server and performs several more javascript actions, before reacting to the users request.

Now i understand that this might not be the most efficient method, or necessarily the industry standard and correct method, but it works for my small use edge case where data security is not much of a concern.
As it turn's out i wasn't too far off the mark but as makeMoney2010 mentioned i couldn't call the aspx.vb file directly so i attached it instead to an empty page and called that page to act as a background processor of information. (Most likely incorrect terminology)
The below code should guide anyone else who doesn't know ajax and vb asp.net but needs for some or other reason that defies the norm to be able to call functions on the server from javascript and return some data from a run time compiled codebehind file.
Core.aspx (Background Processor)
<%# Page Language="vb" AutoEventWireup="true" Src="Core.aspx.vb" Inherits="CoreFunctionality"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Processing Data...</title>
</head>
<body>
Processing Data, Please Wait...
</body>
</html>
Core.aspx.vb (The serverside script)
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
public partial Class CoreFunctionality
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function GetLessonList(ByVal crsName As String) As String
If crsName = "" Then
return String.Format("It's blank Jim.", crsName)
Else
return String.Format("Oodles of list data here!!!", crsName)
End If
End Function
End Class
ClientSide.js (Client side javascript)
function GetSegListFromServer(strData){
$.ajax({
type: "post",
url: "Scripts/Core.aspx/DoSomenthig",
contentType: "application/json; charset=utf-8",
dataType: "json",
//data: '{"selCourse":"'+crsName+'"}',
data: '{"lsnName":"'+lsnName+'", "crsName":"'+crsName+'"}',
success: function(result){
ProcessReturnedData(result.d);
},
error: function (xhr, status, error) {
AjaxErrorAlert(error);
}
});
}
function ProcessReturnedData(){
alert("#TODO:");
}
//Generic Ajax error handler
function AjaxErrorAlert(error){
alert("AJAX Error: "+error);
}

Related

Wanting to create a simple web service/api using only html page to aspx

I have a simple html page where the user enters a FunctionName and it's Parameters and Submits the Call (see HTML text ):.....
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<form action="process.aspx" method="post">
GMailFunction <input type="text" id="GMFunction" name="GMFunction"
GMailParameters<input type="text" id="GMFParameters" name="GMFParameters"
<input type="submit" value="Submit" />
</form>
</body>
</html>
This Call gets answered by an ASPX page named process.aspx containing only this code :
Partial Class _Default
Inherits System.Web.UI.Page
Private Sub _Default_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim GMFunction As String = Request.Form("GMFunction")
Dim GMFParameters As String = Request.Form("GMFParameters")
Response.Write(GMFunction)
Response.Write(<br></br>)
Response.Write(GMFParameters)
Response.Write(<br></br>)
Response.Write("Hello World FROM DEFAULT CLASS")
End Sub
End Class
Questions:
1. In the html code, when I change the method to GET the request does not get treated. What do I need to change in my code ?
2. If I wanted to bypass the HTML page to reach the aspx (like a web api) directly from let's say a windows program, how does the URL need to be formed for a GET and for a POST?
Your calling the Process.aspx page with action="process.aspx" method="post", the events in the codebehind are going to fire in a specific (known) order. Partial Class Process is not one of them, nor is it an event. You have to call it yourself. The simplest way is to call it in the load event, but then how are you going to get the response back to your html page? You're going to need to code some javascript (jQuery is a good library) and maybe some ajax, ajax would probably be better. A lot of what you do can also depend on your development paltform, I assume you're using Visual Studios, if so, what version?
Change your function to a webmethod (plenty of examples on stackoverflow), then call the webmethod using ajax:
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.aspx/SomeWebMethod",
// the parameter names must match webmethod parameter names exactly
data: JSON.stringify({ parameter1Value: 'somedata', parameter2Value: 'moredata' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true
success: function (response) {
alert("Data sucessfully transmited.");
// do stuff here on success like retrieve the data
// easiest way is to set a public variable in the code behind with the data you want to retrieve
// and then set a label's value to the data or some such.
var thedata = '<%=PublicVariableInCodeBehind%>';
// This assumes aspx page is calling the webmethod
$("#<%=SomeLabelName.ClientID%>").val(thedata);
// To set a html label with the data
// $('#labelName').text(thedata);
// You can also do things like add a row and cells to a table and display the data that way, whatever you want to do.
},
error: function (response) {
alert("Error = " + response.responseText);
}
});
</script>

Writing to XML file via AJAX and ASPX page

I am trying to use $.ajax.post using:
$.ajax({
type: "POST",
url: "http://localhost/products/SaveXML.aspx",
data: { name: "John", location: "Boston" }
}).done(function (msg) {
alert("Data Saved: " + msg);
});
});
SaveXML lookes like:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script language="c#" runat="server">
public void testMethod()
{
string sayHello = "hello world";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server"></form>
</body>
</html>
Eventually, I want to pass in some XML and have SaveXML handle it.
Does the code need to be in a code-behind? Does it need to be marked as a web method?
Can someone show me what this should look like please?
Thanks
You can use ASP.NET Page Methods with jQuery.
Check this:
Using jQuery to directly call ASP.NET AJAX page methods
The code needs indeed to be server side code (which doesn't mean you have to have a code behind file - what you have with your testMethod will work just fine, as it is in a server side context).
Since you are posting the data to the .aspx page, there is no need to use a web method. You can use Page_Load or OnInit to get the posted data (via the Request page property) and handle the posted data in it.

Multiple fileuploads with ASP.NET MVC

Hi,
I have implemented this plugin by Steve Sanders from 2008. In my solution I have 3 buttons for 3 uploads and this works just fine. But ist not a perfect fit and the question is if thera is a better solution for me?
What I need is :
Be able to upload multiple files
When the Control Action is triggered It should be possible to work with the files
The enduser should be able to cancel a uploaded file(this is not possible with Steves plugin as far as I know)
Easy to use with ASP.NET MVC
If a post is done to the Control Action and a validation error is thrown back the uploads may not disappear.
Pleas Advice
How about using Uploadify? I have used it before, and it works great. But do notice that it also needs a Flash front-end in order to work...
Take a look at this StackOverflow question - there you'll find more info of how to use it with ASP.NET MVC.
Under the hood the Steve Sanders' plugin uses swfUpload which can support everything you need. His plugin however does not seem to expose all of the features of swfUpload such as canceling uploads.
I use swfUpload to it's full extent on my sites supporting multiple files, canceling uploads, validation without canceling other uploads, etc.
Here's a demo of swfUpload in action where you can cancel uploads
Another option is SlickUpload.
It's not free but definitely worth it in my opinion. I used it in an MVC project recently and was extremely happy with it. Best upload plugin I've ever used + it comes with all sorts of validation helpers.
It's fully customizable too.
Download the trial and have a look for yourself :)
It's not possible with pure ASP.NET.
You need to take JQuery uploadify.
It's the best you can find, trust me, I tried for an entire day.
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="MassUpload.aspx.vb" Inherits="Raumplaner_New.MassUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Mass Upload</title>
<link href="../upload/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type = "text/javascript">
$(document).ready( function()
{
$("#<%=FileUpload1.ClientID%>").uploadify({
'uploader' : '../upload/scripts/uploadify.swf',
'script' : '../cgi-bin/Upload.ashx',
'cancelImg' : '../upload/images/cancel.png',
'folder' : '../upload/temp',
'buttonImg' : '../upload/images/uploadbutton.png',
'width' : '97',
'height' : '22',
'wmode' : 'transparent',
'displayData' : 'speed',
'multi' : true,
'auto' : true,
'simUploadLimit' : 20,
'fileDesc' : 'DWG und SWF - Dateien',
'fileExt' : '*.dwg;*.swf',
'onSelect' : function(event, queueID, fileObj){ EnableObject('FileUpload1');},
'onCancel' : function(event, queueID, fileObj, data){DisableObject('FileUpload1');},
'onComplete' : function(event,queueID,fileObj,response,data){alert(fileObj.name);}
});
$("#startUploadLink").click( function()
{
$('#<%=FileUpload1.ClientID%>').uploadifyUpload();
return false;
});
$("#clearQueueLink").click( function()
{
$("#<%=FileUpload1.ClientID%>").uploadifyClearQueue();
return false;
});
});
</script>
</head>
<body style='background:black;'>
<div id='main'>
<form id="form1" runat="server">
<br/>
<div class="demo">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
Start Upload |
Clear
</div>
</form>
</div>
</body>
</html>
And here's upload.ashx
<%# WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = context.Request("folder")
'If you prefer to use web.config for folder path, uncomment below:
'tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not System.IO.Directory.Exists(savepath) Then
System.IO.Directory.CreateDirectory(savepath)
End If
postedFile.SaveAs((savepath & "\") + filename)
context.Response.Write((tempPath & "/") + filename)
context.Response.StatusCode = 200
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

jQuery Ajax in asp.net

I'm trying to call a static method in c# using jQuery Ajax. I've tried before but now it is not working. I get error status as 200 Ok. Here is my code:
$("#btnSample").live("click", function()
{
$.ajax({
type : "POST"
, data : {}
, url : "jQueryAjax.aspx/SampleMethod"
, contentType : "application/json; charset=utf-8"
, dataType : "json"
, success : function(msg)
{
alert("Success : "+msg);
}
, error : function(error)
{
$("#lblSample").text(error.status);
}
});
});
My Server-side code is:
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
aspx for Button:
<input type="button" id="btnSample" runat="server" value="Show What" />
I've recreated your code on my side.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#btnSample").live("click", function() {
$.ajax({
type: "POST"
, data: {}
, url: "Default.aspx/SampleMethod"
, contentType: "application/json; charset=utf-8"
, dataType: "json"
, success: function(msg) {
alert("Success : " + msg.d);
}
, error: function(error) {
$("#lblSample").text(error.status);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label runat="server" ID="lblSample"></asp:Label>
<input type="button" id="btnSample" runat="server" value="Show What" />
</form>
</body>
</html>
That's a copy and paste. I've tested it in IE8 and it works fine.
The one change I did make was changing your success output to use msg.d This is so it outputs Success : jQuery is Super. msg would NOT cause a crash - it would just output Success : [object Object] (msg is a object that contains a string called d which the return from the static method is called).
I haven't changed your static method at all
This is in my class (remember Default.aspx)
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string SampleMethod()
{
return "jQuery is Super";
}
}
This is sitting inside my Default.aspx.cs file
I tried messing around to get a 200 OK error and the ONLY time I managed this was when I had
, contentType: "application/ json;charset=utf-8"
That has a space between the / and json.
But that isn't in your question. Maybe it is sitting in your code that way and you fixed it in the question?
One thing I see different about your script than the way I use it is wrapping the {} in the data part with quotes.
Try this:
, data: "{}"
Also,
This is a good article with some jquery ajax caveats:
http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Your button is posting back instead of calling the click event. To stop the unintentional postback add e.preventDefault to your click handler. I'd also suggest not using a server side control (ie removing the runat=server) unless absolutely necessary. It just adds unneeded overhead.
I have the same problem too, but when i copy and paste the code into a new project it works fine. I think there should be something wrong with web.config

ASP.NET Forms: Using jquery to post to asp.net page method with parameters

I've seen lots of related questions, but nowhere have I found a simple example of code that passes parameters back to a page method via jquery.
I've looked through some of the examples at encosia.com (thanks, Dave) but still haven't managed to get it working. Here's the code so far:
Updated - added some code to pass in params, but it's still not working.
test.aspx:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>test page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
var intxt = document.getElementById("<%= txtIn.ClientID %>").value;
var params = $.toJSON({ 'inStr': intxt });
$.ajax({
type: "POST",
url: "test.aspx/RunTest",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="Result">Click here</div>
<asp:TextBox ID="txtIn" runat="server"></asp:TextBox>
</form>
</body>
</html>
and in test.aspx.vb:
<WebMethod()> _
Public Shared Function RunTest(ByVal instr As String) As String
Return "this is your string: " + instr
End Function
Update:
The RunTest menthod above is never called. However, if I also have:
<WebMethod()> _
Public Shared Function RunTest() As String
Return "no params here"
End Function
Then the 2nd method IS called.
What am I missing? Is this the wrong approach?
The parameters are case sensitive. Your
var params = $.toJSON({ 'inStr': intxt });
Doesn't match the method signature:
Public Shared Function RunTest(ByVal instr As String) As String
The rest of it looks correct.
I would generally suggest using json2.js' JSON.stringify() to serialize JSON on the client-side, instead of other plugins like $.toJSON. json2.js' API matches the ECMA standard for browser-native JSON support which newer browsers are implementing (IE8 and Fx3.5 so far). So, if you're using JSON.stringify() to serialize your objects, it will automatically upgrade to the faster, native functionality in those browsers.
See https://stackoverflow.com/questions/570962/jquery-ajax-form-submitting
You need to load the textbox by ClientID.

Resources