Calling asp.net server function using jquery ajax - asp.net

Am basically new to jquery. I have a function in aspx code bihind. I need to call it in a button click from aspx page using jquery. The server side function takes no arguement and returns no data.
The function the code behind is :
[WebMethod]
public void BindTreeview()
{
TreeView1.Nodes.Clear();
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(#"C:\ClientDocuments\Ford Retail Ltd\");
// output the directory into a node
TreeNode RootNode = OutputDirectory(RootDir, null);
// add the output to the tree
TreeView1.Nodes.Add(RootNode);
//TreeView1.SelectedValue = hdnSelectedNode.Value;
if (hdnSelectedNode.Value != string.Empty)
{
TreeView1.CollapseAll();
TreeNode searchNode = TreeView1.FindNode("Electricity");
if (searchNode != null)
searchNode.Expand();
}
}
aspx jquery is
$(document).ready(function () {
$('#btnNewFolder').click(function () {
// alert('Clicked');
$.ajax({
url: 'Default.aspx/BindTreeview',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert(1);
},
error: function (result) {
alert("The call to the server side failed. " + result.responseText);
}
});
});
});
When i run appln am getting alert on result.responseText. Where am i getting wrong? Quick response will be highly appreciable.

mark your method as static
public static void BindTreeview()

Related

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

Jquery AJAX doesn't call a code behind method

I am trying to invoke method from code behind via jquery.ajax... but nothing happens, no error's just methood is not invoked.
Maybe important to note I use DotNetNuke.
jQuery(document).ready(function () {
jQuery(window).scroll(function () {
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()) {
InfiniteScroll();
}
});
function InfiniteScroll() {
jQuery.ajax({
type: "POST",
url: "LoadItemsHandler.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
alert('comething happened! :)');
}
}
})
};
I have tried to add handler method to .ascx and .aspx but none works:
[WebMethod]
public static string GetData()
{
return "<div><h2>I am comming in peace from code behind.</h2><p>Lorem ipsum dolor sit amet ... :)</p></div>";
...
I have tried to put alert() in InfiniteScroll() and it's invoked on scrolling, but background method... nothing :(
UPDATE 1
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
public static string GetData()
{
string json = Test("Mike");
return json;
}
And I get:
Error:SyntaxError: JSON.parse: unexpected character
UPDATE 2
Ok I got it.
From code behind I return:
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { NewTotal = "777", OfType = "love" });
On the ajax call success I have:
success: function (data) {
if (data != "") {
alert(data.d);
...
Now this present following data:
{"NewTotal":"777", "OfType":"love"}
And now the only issue I have is how to get NewTotal or OfType value because when I use data.NewTotal I get undefined?
You don't need to convert result to JSON, it is auto. serialized to JSON
[WebMethod()]
public static object GetData()
{
return (new { NewTotal = "777", OfType = "love" });
}
On JS, refer to newTotal like this
data.d.NewTotal
Well, first of all, calling Page methods inside UserControl will not work, so they should be defined in the aspx page.
Secondly, check for errors in firebug.
Also, make sure that you are calling from the same page.
Thirdly, use a webservice (*.asmx)
can use library using Newtonsoft.Json;
JsonConvert.SerializeObject(Request["paramater"])

Add ASP.NET Image from Page Method

I am making an Ajax request with data to a Page Method in my code behind in my ASP.NET Web Forms application. I have a Panel control in my aspx page but I cannot get the control from that Page Method with its ID. I can get it from the Page_Load event though. What can I do to get the Panel control from the page method or is it not possible or maybe an alternative?
<asp:Panel ID="pnlImages" runat="server"></asp:Panel>
<script type="text/javascript">
function GetProductId() {
$.ajax({
type: "POST",
url: "Default.aspx/GenerateQrCode",
data: "{'Products':" + JSON.stringify(data) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (msg) {
alert('Success');
}
});
}
</script>
[WebMethod]
public static void GenerateQrCode(List<Product> Products)
{
foreach(var product in Products)
{
string qrCodeLocation = products.Where(pid=>pid.ProductId == product.ProductId).Select(s=>s.QrCode).FirstOrDefault().ToString();
Image image = new Image();
image.ID = product.ProductId.ToString();
image.ImageUrl = qrCodeLocation;
//Cannot get 'pnlImages' here
}
}
You won't be able to do that, WebMethod doesn't follow the same flow as normal page methods. It's not even a instance method but static.
You'll have to return the information on client and create the image there using javascript.

making ajax call (in jquery) for webservice in asp.net

I want to validate product code for duplication using ajax call(in jquery) for webservice in which web method is written. now if success function executes as 'duplicate product code' it should not allow the user to save record. so how can i check this on Save buttons click event
First, create the below method in the page code behind.
using System.Web.Services;
[WebMethod]
public static bool CheckDuplicateCode(string productCode)
{
bool isDuplicate = false;
int pCode = Convert.ToInt32(productCode);
//check pCode with database
List<int> productCodes = GetProductCodeInDb();
foreach (var code in productCodes)
{
if (pCode == code)
{
isDuplicate = true;
break;
}
}
return isDuplicate;
}
And in the page markup just before the end body tag insert this code
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btnSave.ClientID %>').click(function () {
SaveProduct();
});
});
function SaveProduct() {
//Get all the data that you are trying to save
var pCode = $('#<%= txtProductCode.ClientID %>').val();
//pass the product code to web method to check for any duplicate
$.ajax({
type: "POST",
url: "/InsertProductPage.aspx/CheckDuplicateCode",
data: "{'productCode': '" + pCode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSuccees(msg);
},
error: AjaxFailed
});
}
function AjaxSuccees(msg) {
if (msg.d == true) {
return true;
//insert the rest of data
}
else {
alert("Product code already exists");
return false;
}
}
function AjaxFailed(msg) {
alert(result.status + ' ' + result.statusText);
}
</script>
Hope this helps

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

Resources