1

In my Login Page I want to show error message when user enter wrong email and password without refreshing page. I am trying to send data from view to controller using ajax. But in the controller, user.Email and user.Password are null when I debug, but the Ajax call works. I want to know what is wrong there?

<div class="login-container">
    <div class="row">
        <div class=" col-md-12 col-sm-12 col-12  login-form-1">
            <h2>Login</h2>
            <p>Log into your account</p>
            @using (Html.BeginForm("Login", "Account", FormMethod.Post))
            {
                <div id="alertmessage">
                    <div class=" alert alert-danger">
                        <span>
                        Email or Password is incorrect
                        </span>
                    </div>
                </div>
 
                @Html.AntiForgeryToken()

                <div class="form-group col-md-12 col-sm-12 col-12">
                    <input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
                </div>
                <div class="form-group col-md-12 col-sm-12 col-12 ">
                    <input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
                </div>
                <div class="form-group col-md-12 col-sm-12 col-12">
                    <input type="submit" class="btnSubmit" value="Login now" id="logbut" />
                </div>
                <div class="form-group col-md-6 col-sm-6 col-6">
                    <a href="#" class="ForgetPwd">Forget Password?</a>
                </div>
            }
        </div>
    </div>
</div>

$(document).ready(function () {
    $("#alertmessage").hide()
    $("#logbut").click(function (e) {
        e.preventDefault();
        // collect the user data
        var data = {};
        data.Email = $("#Email").val();
        data.Password = $("#Password").val();

        var token = $('input[name="__RequestVerificationToken"]').val();

        $.ajax({
            url: "/Account/Login",
            type: "POST",
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',   
            data: {
                model: data,
                __RequestVerificationToken: token,
                returnUrl: "Account/Login"   // you can modify the returnUrl value here
            },
            success: function (result) {
                if (result == "Fail") {
                    $("#alertmessage").show()
                }
                else  {
                    window.location.href = "/Account/MainAccount";
                }
            },
        })
    })
})

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User user)
{
    string result = "Fail";

    User appUser = _context.Users.FirstOrDefault(u => u.Email == user.Email);

    if (appUser != null)
    {
        if (appUser.Password ==user.Password)
        {
            Session["ActiveUser"] = appUser;
            return RedirectToAction("MainAccount");   
        }
    }

    return Json(result, JsonRequestBehavior.AllowGet);    
}

user.email and user.Password is null when I debugged it

How can I solve this problem?

2 Answers 2

1

Instead of using User Model in MVC action, use parameters in

Login(string email, string password)

And in Ajax pass

data: 
{ 
    email : email, 
    password : password, 
    __RequestVerificationToken: token
}
Sign up to request clarification or add additional context in comments.

Comments

1

Can you please try this.

Note: you model class property same as inside form control name

Like example

UserName Password

In you example you are sending a request using ajax but your button type is submit when you click on button two requests come in server one is ajax and the second one is form.

Please see this example.

<div class="login-container">
 <div class="row">
<div class=" col-md-12 col-sm-12 col-12  login-form-1">
<h2>Login </h2>
<p>Log into your account</p>
@using (Html.BeginForm("Login", "Account", FormMethod.Post,new {id="LoginFrom" }))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>

@Html.AntiForgeryToken()

<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Email" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Password" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="button" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
<a href="#" class="ForgetPwd">Forget Password?</a>
</div>
}
</div>
</div>
</div>

Jquery Code

$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {   

    $.ajax({
        url: '@Url.Action("Login","Account")',
        type: "POST",          
        data: $("#LoginFrom").serialize(),
        success: function (result) {
            if (result == "Fail") {
            $("#alertmessage").show()

            }
            else  {

                window.location.href = "/Account/MainAccount";
            }
        },
        })
    })
})

For more detail -> check this link https://www.w3schools.com/jquery/ajax_serialize.asp

4 Comments

Thank you for your answer. But there is error: "Failed to load resource: the server responded with a status of 404 (Not Found) localhost:44348/Account/@Url.Action(%22Login%22,%22Account%22)" . I changed url: '@Url.Action("Login","Account")' to url: "/Account/Login". Now it works without error but input values are null again.
Sorry for that i have miss the code in view can you please check again if possible I have update view code. in your view control name "Emaillog" and "Passwordlog" that's the resion for value not bind in model class.
The main issue is main property name not name in model so that control value not mapped.
Welcome bro :) glad to help you.

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.