1

I'm working on a simple website that has a login/sign up feature. I just want to let the user get a message after he successfully sign in or sign up.

Here's my login method

Controller :

[HttpPost]
    public ActionResult Login(string username,string password)
    {
        User loginTest = DB.Users.Where(a => a.User_Name.Equals(username) && a.User_Password.Equals(password)).FirstOrDefault();
        if (loginTest != null)
        {


            //some code
        }
        else
        {
            return Redirect(Request.UrlReferrer.ToString());
        }
    }

I'm calling the login method like this

 @using (Ajax.BeginForm("Login", "Home", new AjaxOptions() { UpdateTargetId = "logged-in", InsertionMode = InsertionMode.Replace }))
                        {
                         <input type="text" />
                         <input type="password" />
                         <input type="submit" value="login">
                         }

Here's my javascript function that I want to run if the logging in is successful.

  <script type="text/javascript">
    function JSalert(){
swal("Logged in successfully");
     }
  </script>

I already added

<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

And I tested the function on button click and it's working, I'm just new to this and I wonder how to call this function after the user log in.

I checked these links already but I couldn't get any help.

Call a javascript function after ajax success

Run javascript function after Postback

Thanks.

6
  • Are you calling Login via AJAX? Commented Feb 12, 2019 at 7:43
  • so learn about ajax Commented Feb 12, 2019 at 7:43
  • 1
    Where is your AJAX request code? Commented Feb 12, 2019 at 7:44
  • You're returning an ActionResult from your actionMethod when the user logs in, which you've not mentioned here, perhaps you can mention that or use AJAX requests to log in and dynamically change the content using JS Commented Feb 12, 2019 at 7:49
  • I edited my question Commented Feb 12, 2019 at 7:57

4 Answers 4

1

Welcome to Stack Overflow. You don't have to use that Ajax.BeginForm. You can write some pure HTML.

<form>
    <input type="text" id="username" placeholder="login">
    <input type="text" id="password" placeholder="password">
    <input type="button" value="Log In" id="postIt">
</form>

In order to make Ajax call, add some JavaScript/jQuery code into the same cshtml file.

<script>
$("#postIt").click(function() {
    postIt();
});
function postIt() {
    var usr = $("#username").val();
    var pwd = $("#password").val();
    $.ajax({
        type: "POST",
        url: "/Login/LogMeIn",
        data: { "Username": usr, "Password": pwd },
        success: function(data) {
            if (data.result) {// logged in
                JSalert(data.result);
            } else {// unauthorized
                JSalert(data.result);
            }
        }
    });
}
function JSalert(msgType) {
    if (msgType) {
        swal("Logged in successfully", "Welcome to StackOverflow", "success");
    } else {
        swal("You're not authorized", "Welcome to StackOverflow", "error");  
    }
}
</script>

Then, add a simple login method into the controller.

[HttpPost]
public JsonResult LogMeIn(LoginModel data)
{
    if (data.Username == "rightUser" && data.Password == "rightPass")
    {
        return Json(new { result = true, message = "welcome" });
    }
    return Json(new { result = false, message = "unauthorized" });
}

LoginModel.cs

public class LoginModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    ...
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>
Sign up to request clarification or add additional context in comments.

8 Comments

Very understandable, but i guess in this way it will show me and simple alert message, what if I want to show my function which is JSalert()
I've edited the answer. It includes the alert function and more information about project structure now.
one last thing, what do you mean by LoginModel data, because in my project I have a big viewModel that contains loads of data(tables,lists...), so is there any way to pass the username and the password like I did before :(string username, string password) ,thanks in advance
I've edited the answer again, you can see and clone that LoginModel. Also, don't forget the take a look at secure authentication mechanisms when you get this concept.
I created a new LoginModel like you did, but the data passed into LogMeIn is always null
|
0

You can use:

   using (Ajax.BeginForm("Login", "Home", new AjaxOptions { HttpMethod = "Post",  OnSuccess = "onSuccess" })){
       //your code
    }

In your js:

function onSuccess(result) {
   //return your message here
}

4 Comments

I did this but the js function is not being called
Is there any error in console? Make sure you have tagged your actionmethod with [HttpPost]
I added <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> and now it's working, but it's showing me the alert message even when the username and password are incorrect
You can return flag from controller whether it is success or not and you will get it in result parameter of JS function
0

There are several ways to show alert or any message after the redirection.

  1. You can set some flag in query string while redirecting the user. In your java-script code, check if the flag exists, show user the message.
  2. Set a java-script variable in while rendering the view and check that variable to show message or not.
  3. You can also use local-storage or create a cookie, but that is never preferred.

In your redirect statement use the below code

return Redirect(Request.UrlReferrer.ToString()+"login_success=1");  

In your ajax success, use the below code, it will work

if(window.location.href.indexOf("login_success=1")){
//call your function
}

3 Comments

I'm super new to this, can you show me how to do that?
are you using an ajax call on form submit?
Yes, i'm using Ajax.BeginForm
0

Use this Method

@using (
Ajax.BeginForm("Register", "Account", null, new AjaxOptions(){
HttpMethod = "POST",OnSuccess = "OnSuccess" 
}, new { 
@class = "form-horizontal", role = "form" 
}))
{
}

JS Function:

 function OnSuccess(response) {
        if (response.status === 'validationerror') {
           //your code
        } else {
           //your code
        }
    }

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.