I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'
Related
I know that it is possible to send an AJAX request to an .asmx page. And I also know that an .asmx page handles an AJAX request via a web method.
Is it also possible to send an AJAX request to an .aspx page? If so, does an .aspx page also handle an AJAX request via a web method? Note that I would like to return a JSON response from the .aspx page. Is this possible?
You can define web methods in the code-behind of your .aspx page and then call them:
[WebMethod]
public static string doSomething(int id)
{
...
return "hello";
}
And then, to call a web method in your jQuery code:
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
Here is a good link to get started.
if i understood question correctly, Aspx is same as HTML. It will be rendered as HTML. but only difference is Server Side and Controls retaining the states with state mechanism.
so you can do jquery $.ajax() function.
$.ajax({
url: UrlToGetData,
dataType:'json',
success:function(data){
//do some thing with data.
}
});
or if you want to write out json value to the response, then use Response.ContentType
first use any Javascript serializer(JSON.NET) , then set the contentType like this.
Response.ContentType="application/json";
$.ajax({
url: "(aspx page name/method to be called from the aspx.cs page)",
type: "POST",
dataType: "json",
data: $.toJSON(jsonData),
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
//TO DO after success
}
});
Try the above code
I have used whole lots of options resolving this, but it is not working.
My breakpoint is not hit in the Web Method. Also, the success function is being called, however, entire page content is returned not the string "hello".
My page does not at all use asp.net ajax scriptmanager. It uses plain jQuery only. I am using ASP.NET 4.0.
In brief, my page method is defined as:
[WebMethod]
public static string Populate()
{
return "hello";
}
The ajax call is:
$.ajax({
url:'WebForm3.aspx/Populate',
data:{},
dataType:"json",
type:"GET",
success: function(msg) {
alert("success");
},
error: function(msg, text) {
alert(text);
}
});
Page methods only work when POSTed to, like this:
$.ajax({
url:'WebForm3.aspx/Populate',
data: '{}',
dataType:"json",
type:"POST",
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert("success"); },
error: function(msg, text) {
alert(text);
}
});
Don't forget to quote the data argument: data: '{}'.
I'm trying to send my form to a web method in asp.net page using jquery.forms plugin (primary reason for that is that I need to send files as well).
However, I can't make it work - it returns the whole page all the time.
I use the following client-side code:
<script type="text/javascript">
var ajaxUploadOptions = {
beforeSubmit: UploadFormValidate, // pre-submit callback
success: FormUploadSuccess, // post-submit callback
error: FormUploadFailure,
url: "Default.aspx/UploadFiles", // override for form's 'action' attribute
type: "POST", // 'get' or 'post', override for form's 'method' attribute
dataType: "json", // 'xml', 'script', or 'json' (expected server response type)
contentType: "application/json; charset=utf-8",
};
function FormUploadSuccess(response, statusText, xhr, jqForm) {
alert(response);
};
function FormUploadFailure(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
$("form[id $= 'form1']").ajaxForm(ajaxUploadOptions);
});
</script>
Code for the asp.net method just to return anything:
[WebMethod]
public static string UploadFiles()
{
return "Test";
}
I registered ScriptModule in web.config (also verified just calling regular jquery's $.ajax to make sure the method is available).
Any suggestions would be appreciated.
Thanks!
It seems I haven't read documentation/code carefully enough. Found out that when sending files, the forms plugin uses iframe and regular submit.
I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
});
return false;
});
</script>
Action method on controller:
public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
{
//create an envelope object and return
return Json(envelope);
}
If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?
You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
// IMPORTANT: return false to make sure the normal post doesn't happen!
return false;
});
return false;
});
</script>
You were almost there!
I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?
I am creating Menu in the master page using JQuery. i am passing the id of the link to jquery using $.ajax({});
Problem:
Getting failed: Showing error message in AjaxFailed(result) function.
Code:html[JQuery]
$.ajax({
type: "POST",
url: "Master.Master.cs/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}
c# Code:Codebehind
private static List<string> xx;
[WebMethod]
public static List<string> UserStatus()
{
return xx;
}
protected void Page_Load(object sender, EventArgs e)
{
xx = new List<string> {"#ll1", "#ll2" };
}
What the webmethod attribute does is to say that this method should respond to a certain url (a little bit like routing in asp.net mvc). As I don't use webforms I don't really know what logic it uses when it decides what url the method should respond to. But my guess is that the url should be something like "Master.cs/UserStatus" (not sure about the .cs extension). And that is of course a relative url, so you can try something like this: <%=ResolveUrl("~/Master.cs/UserStatus")%> (if the masterpage is in your root folder). Then your example should be something like this:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/Master.cs/UserStatus")%>',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
Update
The .cs extension is probably wrong. But I don't think you should have that in a master page anyway. You should probably have it in a web service or in a .ashx handler or something if you want to use ajax. But with you last comment it seems that you don't need to use ajax (and if you don't need that, you shouldn't). The problem in the code you wrote in the comment is probably that the id is wrong (remember that you need the client id in javascript).
But I would probably do it something like this:
<script type="text/javascript">
var statuses = [];
<%foreach(var status in UserStatus()) {%>
statuses.push(<%=status%>);
<%}%>
</script>
This will render this javascript in the browser:
<script type="text/javascript">
var statuses = [];
statuses.push("#ll1");
statuses.push("#ll2");
</script>
Then you will have your statuses in the statuses array.
Like Andre and Mattias mentioned, the .cs extension is not served, so you would have to use a .aspx extension to get to the WebMethod.
The problem I see in your example is that you are placing the method in the MasterPage (which would have a .master extension) which is also not served, so you can't call the web method from it.
A workaround you could use is to define it in a class that inherits from Page, and have all of your pages inherit from that class. Since its a public method, it will be public on all of your pages and therefore available. Basicly, a base page for your project's pages. In that case you would only need to use your current page's address to make the call. This is only usefull if it's something you will use on every page, like a menu.
A second workaround you can use is to define the WebMethod in a .asmx Webservice placed in the project. It would work like calling the WebMthod on a page, only you would have to use the .asmx Webservice's address instead of the page's to make the call.
If you've not done so you will need to add the [ScriptService] attribute to your webmethod as this
Indicates that a Web service can be
invoked from script
See ScriptServiceAttribute
I think that the problem is that you try to post to the .cs file. The extension .cs is not served by ISS due to security reasons. So even though your method lifes in the code behind file, you have to post to the .aspx file. ASP.NET will do the rest for your.
So try:
$.ajax({
type: "POST",
url: "/Master.Master.aspx/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}