JQuery and ASP.Net - asp.net

Well im trying to return a more complex type than a string or bool but i fail what am i doing wrong?
JavaScript
<script language="javascript" type="text/javascript">
///<Reference Path="~/Script/jquery-1.3.2-vsdoc.js" />
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Test.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.Name);
},
failure: function() { alert("Failed") }
});
});
});
</script>
C# (This is not a webservice just a normal webpage)
[WebMethod]
public static ImageDC GetDate()
{
ImageDC dc = new ImageDC();
dc.Id = 1;
dc.Name = "Failwhale";
dc.Description = "Hurry the failwale is going to eat us!";
dc.IsPublic = true;
return dc;
}

I'm not sure what version .NET your running, but there is a breaking change with object returned from a web service. Check out this article.
http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
If you use fiddler to look at the request/response, it should be easy to tell if this is the problem.
http://www.fiddler2.com/fiddler2/

You should return a string.
return "dc = {Id:"+dc.Id+", Name:" + dc.Name +", Description: " +dc.Description + ", IsPublic: " +dc.IsPublic "}";

Related

WebMethod access page control and set value

My page name
public partial class AtamaGorevDegistir : System.Web.UI.Page
{}
My webmethod ajax side
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});
My webmethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
AtamaGorevDegistir atama = new AtamaGorevDegistir();
atama.AtananSuren.Value = "123";
return null;
}
But my problem my Control is null . But i can access this method but didnt set value and give error message. Why this happened?
WebMethod and ScriptMethod can't access the controls collection of the calling page. Think of it as outside the normal Web Forms lifecycle. When you use AJAX, you need to pass all data to the server side method it needs, and your server side should return all data that the client side needs. Then the client side should take that returned data and manipulate the DOM as necessary to display the result.
In your WebMethod, return the data instead of trying to assign it to a control, remove the return null;.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string KisiBilgiDoldur(string KayitID, string TeklifID)
{
return "123";
}
In your client side success handler, get the returned data and set the value of the control using JavaScript.
var path = getLocation(location.href);
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
// data: "{" + str + "}",
contentType: "application/json; charset=utf-8",
// dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
//set control value to data.d here
}
});
You don't set the control value with a webmethod. Your return a value and from the api and do something with it, in the browser. Working with webmethods are not like webforms. The value you return in your webmethod is null... you're setting that null value into 'dd' in js, but you don't do anything with it. When you get your value back from the webmethod you need to do something with it. try 'alert(data.d)' in your success callback to see what i mean. Then $('#elm').text(data.d) if you want it on the page.
You should add parameters to data.
$.ajax({
type: "POST",
url: path.pathname + "/KisiBilgiDoldur",
data:JSON.stringify({ KayitID: '1', TeklifID:'2' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var dd = data.d;
$('.modal-dialog').css({ width: '85%' });
$('#AtamaModal').modal({ show: true });
}
});

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.

2 page methods on an aspx page

I'm calling a page method with jquery and it works just fine. I'm creating a second one and it's not working at all; all I get is the error function. Is it possible to put more than 1 page method in an aspx page?
Here's my jquery on the client:
function LoadCount() {
var TheObject = $.toJSON(CurrentForm);
var TheParameter = "{'TheParameter' : '" + TheObject + "'}";
$('#testobj').html("loading");
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetCount",
data: TheParameter,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
function successFn(thedata) { $('#result').html(thedata.d); };
function errorFn() { alert("problem getting count"); };
function LoadData() {
var ConfirmLoad = "test";
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/GetLoaded",
data: ConfirmLoad,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successLoad,
error: errorLoad
});
};
function successLoad(thedata) { alert((thedata.d)); };
function errorLoad() { alert("problem getting loaded"); };
And on the server side, I have this:
[WebMethod]
public static string GetCount(string TheParameter)
{
// some code
return JsonResult;
}
[WebMethod]
public static string GetLoaded(string ConfirmLoad)
{
return "test string";
}
LoadCount and GetCount work great, I thought I'd copy the implementation to create another page method but the second time, nothing good happens. Thanks for your suggestions.
You need to set dataType: "text" in the $.ajax() call properties if you're just returning plain text instead of a JSON encoded string.
You might also want to leave the contentType unspecified (at the default value of 'application/x-www-form-urlencoded') if your're sending plain text instead of a JS object.

issue to send text using jquery's $.ajax() and ASP.Net

I use to work with the animation on jquery but never ajax, so it's my first experience with $.ajax() function of jquery:
I am trying to make my web application only using jquert library, I checked over the web for a good tutorial to make asp.net and jquery work, and I found an walkthrought, in this article they send a int to an WebMethod and it work for me, but in my case I want to send String and/or objects.
I know the issue is int the datatype and/or contentType.
here is my code sample.
<script type="text/javascript" src="scripts/jquery-1.4.1.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#name").change(function() {
var myname = this.value;
var options = {
type: "POST",
url: "dollarajax.aspx/hello",
data: "{nom:" + myname + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != "") {
alert(response.d);
$("#name").focus();
}
}
};
$.ajax(options);
});
});
</script>
[WebMethod]
public static string hello(String nom)
{
return ("hello my friend: " + nom);
}
so any idea or any document where i can figure the trick to make it work?
thanks
Try to change the data like this:
data: '{"nom":"'+ myname +'"}',
instead of:
data: "{nom:" + myname + "}",

Escape character and error 500

I have a problem with some basic ajax and asp.net web service. In my website page i have a text box that is reach text editor, when i put text and try to submit it, ajax supposed to take the text and pass it to asp.net web service. When the sentence contains no escape characters it goes well, however when it does contains escape character the asp.net web service gives me error 500. On debug it doesn't even enters into web service.
So the question is: How can i fix it ?
Here is the code that i have.
Javascript:
//posting the user comment
function postComment() {
var comment_body = $("textarea[id*='txt_editor']").val();
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: "{'article_id': '" + article_id + "', 'comment_body' : '" + comment_body + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
}
And the web service looks like that:
//posting the comment to database
[WebMethod]
public int postComment(int article_id, string comment_body)
{
try
{
using (ForMarieDataContext forMarie = new ForMarieDataContext())
{
tbl_article_comment newComment = new tbl_article_comment();
newComment.article_id = article_id;
newComment.comment_author = "Dmitri";
newComment.comment_date = DateTime.Now.ToString();
newComment.comment_body = comment_body;
forMarie.tbl_article_comments.InsertOnSubmit(newComment);
forMarie.SubmitChanges();
}
return 1;
}
catch(Exception ex)
{
return 0;
}
}
}
This is the basic code and i will add more to it to check for security.
However for now, i need to somehow do something with the escape characters in text.
Thanks in advance.
Let jQuery handle the escaping and encoding of the parameters:
$.ajax({
type: "POST",
url: "Article.asmx/postComment",
data: { article_id: article_id, comment_body: comment_body },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
page_num = 1;
getComments();
clearComment()
}
});
Pay attention to the data property.

Resources