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.

riario
  • 51
  • 3
  • 11

4 Answers4

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>
  • 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() – riario Feb 12 '19 at 08:47
  • I've edited the answer. It includes the alert function and more information about project structure now. –  Feb 12 '19 at 09:03
  • 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 – riario Feb 12 '19 at 09:16
  • 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. –  Feb 12 '19 at 09:30
  • I created a new LoginModel like you did, but the data passed into LogMeIn is always null – riario Feb 12 '19 at 09:37
  • Is there any other form in the same page? What is the type of your button? And, make sure that there is no typo in your HTML code. –  Feb 12 '19 at 10:40
  • No, but there are many contents in the page that are loading from the viewmodel – riario Feb 12 '19 at 12:18
  • It's difficult to comment without further details. Just try it with a new controller and view in order to see what's going on. –  Feb 12 '19 at 14:01
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
}
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
}
Ankita
  • 1,416
  • 4
  • 17
  • 42
  • I did this but the js function is not being called – riario Feb 12 '19 at 08:20
  • Is there any error in console? Make sure you have tagged your actionmethod with **`[HttpPost]`** – Ankita Feb 12 '19 at 08:38
  • I added and now it's working, but it's showing me the alert message even when the username and password are incorrect – riario Feb 12 '19 at 08:41
  • You can return flag from controller whether it is success or not and you will get it in **result** parameter of JS function – Ankita Feb 12 '19 at 08:43
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
        }
    }
codingbbq
  • 4,049
  • 5
  • 35
  • 47