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

16
  • 1
    add break point to loadEmployeeAccount ass see where is error occurred in which line. Commented Mar 27, 2019 at 6:20
  • @MohammadAlghanem the debugger cannot hit the breakpoint. Commented Mar 27, 2019 at 6:22
  • @MohammadAlghanem Please see 2nd image sir Commented Mar 27, 2019 at 6: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 Commented Mar 27, 2019 at 6:35
  • @DavideVitali I already change the method sir, but again nothing happens and it always reloading when i click the button login Commented Mar 27, 2019 at 6:44

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

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))
        }
    });
}

1 Comment

Nothing happens sir.
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’

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.