jQuery Ajax in asp.net - 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

Related

Ajax connection with asp.net codebehind and runtime compilation trouble

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);
}

Dealing with a Large Number of Post Variables ASP.Net

I am running into an issue where I have multiple forms with a number of controls on them (20-40). The problem is that when I handle the postback, I need to put their values into variables and if they are not asp.net server controls (i.e select, input, etc...) I sometimes need to make sure they even exist. So, if I have a plain html checkbox, which is unchecked, it will not be posted to the server and you need to check for its existence, before being able to get its value. After that I need to pass them into a method to save to the database. The method handles all my crud and business validation. Setting this up is tedious at best and very time consuming. What are people doing to handle this? I am using ASP.Net 4.0 Web forms and VB.Net. One thought was to pass the http context into the method and let the code in the method look for the values. Still, doesn't seem that good of a solution. Any advice would really be appreciated, since I know I am not the only one who has run into this problem. Thanks in advance.
Wade
For large forms, you can:
create javascript object on client, convert it to JSON string, put JSON string to ASP .NET control Hidden or invisible textarea;
submit form and deserialize JSON to object on server.
Default.aspx
<%# 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="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validation.net.webforms.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="Hidden1" />
<input type="checkbox" id="CheckBox1" checked />
<input type="checkbox" id="CheckBox2" />
<input type="text" id="text1" name="text1" value=""/>
<asp:Button runat="server" Text="Button" ID="Button1" OnClientClick="createJSON()" OnClick="Button1_Click" />
<script type="text/javascript">
function createJSON() {
$('#Hidden1').val(JSON.stringify({
field1: $('#CheckBox1').is(':checked'),
field2: $('#CheckBox2').is(':checked'),
field3: $('#text1').val()
}));
}
$(document).ready(function () {
$("#form1").validate({
onsubmit: false,
rules: {
text1: {
required: true,
digits: true
}
}
});
$("#Button1").click(function (evt) {
var isValid = $("#form1").valid();
if (!isValid) evt.preventDefault();
});
});
</script>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.Script.Serialization;
public class myClass
{
public bool field1;
public bool field2;
public string field3;
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var result = (myClass)(new JavaScriptSerializer()).Deserialize(Hidden1.Value, typeof(myClass));
}
}
Install validation:
PM> Install-Package JQuery.Validation
PM> Install-Package JQuery.Validation.WebForms
From the moment that some controls they not post back any value, like the check box if is not checked you have two options.
Know all your controls before and after the post back / or
Create with javascript all the names of the controls and post them back in a hidden field.
Now, on the post back you have all the posted values on the HttpContext.Current.Request.Form where you can read them all.
On the client side you can use simple javascript or jQuery to create the list of all input controls and send them on a hidden input. Here is an example:
var inputs, index, cNames = "";
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
cNames += "&" + inputs[index].name;
}
document.getElementById("AllControls").value = cNames;
or the same with jQuery
var cAllNames = "";
$('input').each(function() {
cAllNames += "&" + $(this).attr("name");
});
jQuery('#AllControls').val(cAllNames);
and on your page you have a hidden control like
<input type="hidden" name="AllControls" id="AllControls" />
and on the post you have all the names of your controls in a line like:
AllControls=&__VIEWSTATE&__EVENTVALIDATION&cbBoxTest&AllControls&Button1
There you can split that string, each name is seperated with the &, and there you can see what is used, what is not. You can either pass additional informations about that controls - the same way I send the name of each.
For each web form create a model class that has public properties with all the fields that may be on the form. Create name, validation and default value attributes and apply them to the properties. During the postback, find out what the model class is needed, create an instance, iterate its public properties and apply: if post has the field with property name - validate the value and apply to the field, if not - apply the default. Something like (i'll use c# but I guess it's clear anyway)
MyCrudModelForSomeForm {
[MyWebFormField(Default = 42, Type = typeof(int), Name = "txtAmount")]
public int SomeInt { get; set; }
[MyWebFormField(Default = "Hello", Type = typeof(string), Name = "txtMessage", Validate = "$[A-Z]{6}^")]
public string SomeString { get; set; }
[MyWebFormField(Default = "Zimbabwe", Type = typeof(string), Name = "txtCountryChoice")]
public string SomeOtherString { get; set; }
}
That's basically the custom implementation of M(odel) from MVC concept.
The ASP.NET Webforms arch does not support multiple forms
If you have created a page that has multiple forms then i would suggest use jQuery and Post Individual form to the respected handler to process the request
This will be simple and elegant

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.

div onclick without full page reload?

i am using < div onclick="""> to call the server side .How can i avoid full page refresh when user click the < div>?
Here is my coding.
HTML
<asp:UpdatePanel ID="updatePanel1" runat="server"> <ContentTemplate>
<div id ="cde" runat="server" style="background-color: #00FFFF" > </div>
<asp:Label ID="Label1" runat="server" Text="Label"> </asp:Label>
</ContentTemplate> </asp:UpdatePanel>
Server side
protected void Page_Load(object sender, EventArgs e)
{
//--Register for div onclick function --
cde.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "divMember_Click");
//**Register for div onclick function**
}
protected void divMember_Click()
{
this.Label1.Text = System.DateTime.Now.ToString();
}
public void RaisePostBackEvent(string eventArgument)
{
if (!string.IsNullOrEmpty(eventArgument))
{
if (eventArgument == "divMember_Click")
{
divMember_Click();
}
}
}
I try putting the label within the update panel . But postback will still occur. How can i refresh the label without full page reload?
you can use Jquery .ajax function or pagemethod.YourWebMethod.
Create Web Method in your C# Code and call it using these two functions.
You can do Page Method by EnabledPageMethod="true" in script Manager and use Jquery .ajax function put jquery java script.
This will be on page behind code (create Web Method):
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
As referenced in Default.aspx, this is java script:
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
<head>
<title>Calling a page method with jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="Default.js"></script>
</head>
<body>
<div id="Result">Click here for the time.</div>
</body>
Put the div and Label into UpdatePanel
Try this way,
Keep your label in the Update Panel id"Updatepanel1" with following properties
Update Mode : Conditional
EnableViewState : true(if you are using it)
You need to have an asp:ScriptManager present on your page to use UpdatePanel. See here.

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