0

I am beginner in developing a website using ASP.Net

Please Help me. so that i can pursue my career. Thanks in Advance

I am creating a login script using c# and I want to call it in javascript.

But it after I Logged in, The Login page will only refreshing.

And there is an exception said Exception thrown: 'System.InvalidOperationException' in System.Web.Extensions.dll

So here is my code :

HTML

<form>
                <div class="form-group">
                  <input type="text" class="form-control material" id="username" placeholder="Username">
                </div>
                <div class="form-group">
                  <input type="password" class="form-control material" id="password" placeholder="Password">
                </div>

                <button type="submit" id="btnLogin" class="btn btn-block btn-info text-uppercase waves">Login</button>

              </form>

JAVASCRIPT:

$(document).ready(function () {
    $("#btnLogin").click(function () {
        var username = $("#username").val();
        var password = $("#password").val();
        AuthenticateUser(username, password)
    });
});

function AuthenticateUser(username, password) {
    var value = "{'email':'" + username
                   + "','pass':'" + password
                   + "'}";
    $.ajax({
        type: 'POST',
        url: '../WebService/csLogin.asmx/loadEmployeeAccount',
        dataType: 'json',
        data: value,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            var cells = eval("(" + response.d + ")");
            console.log(cells);
            if (cells.length >= 1) {
                    window.location.href = "index.html";
            } else {
                alert("Invalid Email/Password");
                document.getElementById("username").focus();
            }
        },
        error: function (error) {
            alert(JSON.stringify(error))
        }
    });
}

C#:

[WebMethod]
    public string loadEmployeeAccount(string email, string pass)
    {
        List<Auth> mylist = new List<Auth>();
        using (MySqlConnection connection = new MySqlConnection(connectionString()))
        {
            connection.Open();
            MySqlCommand cmd = new MySqlCommand("SELECT * FROM user WHERE username = @email AND password = @pass", connection);
            cmd.Parameters.Add("@email", MySqlDbType.VarChar).Value = email;
            cmd.Parameters.Add("@pass", MySqlDbType.VarChar).Value = pass;
            cmd.CommandType = CommandType.Text;
            cmd.CommandTimeout = 0;

            MySqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                int user = 0;
                if (dr["userType"].ToString() == "")
                    user = 1;
                else
                    user = Convert.ToInt32(dr["userType"].ToString());
                mylist.Add(new Auth
                {
                    user_id = dr["user_id"].ToString(),
                    username = dr["username"].ToString()
                });
            }
            dr.Close();
            connection.Close();
        }
        JavaScriptSerializer jss = new JavaScriptSerializer();
        string jsn = jss.Serialize(mylist);
        return jsn;
    }

And here is the image on the console. enter image description here enter image description here Can someone help me with this?? any help will much be appreciated. Thanks

Boo La Teh
  • 77
  • 1
  • 7
  • 1
    add break point to loadEmployeeAccount ass see where is error occurred in which line. – Mohammad Ghanem Mar 27 '19 at 06:20
  • @MohammadAlghanem the debugger cannot hit the breakpoint. – Boo La Teh Mar 27 '19 at 06:22
  • @MohammadAlghanem Please see 2nd image sir – Boo La Teh Mar 27 '19 at 06:26
  • 1
    The error is right there, at the 4th point of the error webpage. You’ve used a POST method on the page request, but you should’ve used GET – Davide Vitali Mar 27 '19 at 06:35
  • @DavideVitali I already change the method sir, but again nothing happens and it always reloading when i click the button login – Boo La Teh Mar 27 '19 at 06:44
  • @BooLaTeh the Ajax call has POST type, what have you changed? – Davide Vitali Mar 27 '19 at 06:46
  • @DavideVitali this one sir `type: POST` to `type: GET` – Boo La Teh Mar 27 '19 at 06:50
  • @DavideVitali I tried to breakpoint my c# code sir. but the debugger does not hit it. what should be the possible cause of this? – Boo La Teh Mar 27 '19 at 06:55
  • Instead of [WebMethod] use [HttpPost] in your C# code. Also if you want to send JSON via Ajax, you would need to do `data: { "json": JSON.stringify(value) }` and then in your C# code it would be `[HttpPost] public string loadEmployeeAccount(string json){//your code with json string}` – Rahul Sharma Mar 27 '19 at 06:58
  • @RahulSharma the `[HttpPost]` is underlined by red. is there any reference that i need to remove the error? – Boo La Teh Mar 27 '19 at 07:32
  • @RahulSharma `Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'UseHttpPost' could not be found (are you missing a using directive or an assembly reference?) benchmark(1) C:\Users\SDG08\Desktop\benchmark\App_Code\wsLogin.cs 27 Active` Error still exist – Boo La Teh Mar 27 '19 at 07:38
  • @RahulSharma Sir? how to split and get the username and password in your code in c# `data: { "json": JSON.stringify(value) }` – Boo La Teh Mar 27 '19 at 07:39
  • In your C# code, once you have you JSON string which is `json`, you can do something like this `dynamic jsondata = serializer.Deserialize(json, typeof(object));` and then do get your username and password: `string username = jsondata["email"]; string password=jsondata["pass"]` – Rahul Sharma Mar 27 '19 at 07:42
  • Sorry didn't realize you are using ASP.NET ASMX: Using `[WebMethod]` is fine on your C# code. Add the following references to your web.config file: ` ` – Rahul Sharma Mar 27 '19 at 07:47
  • It always error sir – Boo La Teh Mar 27 '19 at 07:48
  • how about https://stackoverflow.com/questions/37147406/http-error-405-0-method-not-allowed-in-iis-express – Aristos Mar 27 '19 at 07:55

3 Answers3

1

Okay, in order to achieve your functionality follow these steps:

In your AJAX, do the following to convert your value string as JSON and then send it to your WebMethod:

data: {"json": JSON.stringify(value)}

Then decorate your class with:

[System.Web.Script.Services.ScriptService]

to allow POST requests via AJAX to your WebMethod.

And then in your WebMethod, do the following to parse your JSON string that you received from your AJAX call:

[WebMethod]
public string loadEmployeeAccount(string json)
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string username = jsondata["email"]; 
string password=jsondata["pass"]

//Your code here
}
Rahul Sharma
  • 3,860
  • 2
  • 18
  • 33
0

it seems there is issue in passing value from ajax call please make change in your javascript function to call webmethod

function AuthenticateUser(username, password) {
    var value = {'email':username,
                 'pass':password};
    $.ajax({
        type: 'POST',
        url: '../WebService/csLogin.asmx/loadEmployeeAccount',
        dataType: 'json',
        data: JSON.stringify(value),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            var cells = eval("(" + response.d + ")");
            console.log(cells);
            if (cells.length >= 1) {
                    window.location.href = "index.html";
            } else {
                alert("Invalid Email/Password");
                document.getElementById("username").focus();
            }
        },
        error: function (error) {
            alert(JSON.stringify(error))
        }
    });
}
Kevin Shah
  • 1,549
  • 1
  • 13
  • 20
0

I’m not familiar with pure ASP.NET, as I use MVC, but I guess they’re just the same under the hood, so this is a wild guess.

First thing, within your Ajax function you have to change the type of action from POST to GET, your error webpage is explicitly telling you you’re not supposed to send data through a POST action, after all.

type: ‘GET’

Second thing, i think the way you’re passing data to the web method is wrong: you’re passing a single literal object when your method is expecting two strings. By changing this, things should work as expected:

data: {
    email: username,
    pass: password
}

also, delete the dataType: ‘JSON’

Davide Vitali
  • 835
  • 5
  • 18