1

I'm with troubles to connect javascript with asp.net webforms method via ajax and json.

I have the javascript in one folder and page.aspx in the other for example: - Account/createUser.aspx - Script/actions/createuser.js

I already tried many things, for example, use before the method [Webmethod], in the ajax action change many things, but nothing works. In mostly of tentatives the google chrome give the error:

POST .../Account/createUser.aspx/CheckUserName 401 (Unauthorized)

If I remove in javascript lines like: "dataType: json" and "contentType: application/json; charset=utf-8" the error disappears and enter on "complete" line...

I need instructions to resolve this problem... I search a lot of posts, follow many tutorials and nothing means work. For example: change my webconfig to accept any users, my routeconfig.cs...

Is something faling? What? Do I need to declare something to use json?

Javascript:

$("#USUserName").change(function () {
    alert($("#USUserName").val());
    $.ajax({
        type: "POST",
        url: "createUser.aspx/CheckUserName",
        data: '{username: "' + $("#USUserName").val() + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        complete: function (jsondata, stat) {
            if (stat == "success") {
                var response = JSON.parse(jsondata.responseText).d;
                alert((response));
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert();
        }
    });

aspx.cs code:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string CheckUserName(string username)
    {
        var existUser = context.user.Where(us => ((us.username).Equals(username))).Count();
        string returnValue = string.Empty;
        if (existUser.Equals(0))
        {
            returnValue = "test- yes!";

        }
        else
            returnValue = "test- no!";
        return returnValue;
    }
  • Maybe this is running in different domains? If yes then you have stomped with cross domain security, jsonp could help you. – Gusman Apr 22 '14 at 00:10
  • Different folders are not different domains. – Gusman Apr 22 '14 at 00:26
  • 1
    First suggestion: Depending on your browser, Install Firefox+Firebug, or Fiddler, or Chrome + Web Developer Tools + JSONview. These will give you visibility into your AJAX requests. Otherwise, you are flying blind as a developer. – codenheim Apr 22 '14 at 00:27
  • take a look here: http://stackoverflow.com/questions/18244696/how-to-return-json-with-asp-net-jquery – frenchie Apr 22 '14 at 00:43
  • also: http://stackoverflow.com/questions/8405458/return-json-data-from-asmx-web-service – frenchie Apr 22 '14 at 00:44

2 Answers2

0

You need to use the WebMethod attribute to be able to call with ajax (if domain is the same).

C#

public partial class PageName: Page 
{
  [WebMethod]
  public static string MethodName()
  {
    return "success";
  }
}

JS

$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});-

source : http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

If domain is different, you have to edit the cross domain policy : http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Yooz
  • 2,506
  • 21
  • 31
  • The domain is the same. but give the same error: POST http://localhos(...)/Account/createUser.aspx/GetDate 401 (Unauthorized) –  Apr 22 '14 at 09:27
  • I just tried again, it works fine. Can you make sure that your method is PUBLIC and STATIC? – Yooz Apr 22 '14 at 22:49
0

See MS docs:

The ScriptMethodAttribute attribute is optional. (However, methods that can be called from client script must have the System.Web.Services.WebMethodAttribute attribute applied.). If a method is not marked with ScriptMethodAttribute, the method will be called by using the HTTP POST command and the response will be serialized as JSON. You cannot override this setting from script.

If you just want JSON and are using an HTTP POST method, remove the optional [ScriptMethod ...] and make sure you just have [WebMethod]

http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptmethodattribute.aspx

codenheim
  • 20,467
  • 1
  • 59
  • 80