Aytac
Aytac

Reputation: 335

Input values are null in controller(ASP.Net MVC) using ajax

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?

Upvotes: 1

Views: 173

Answers (2)

jishan siddique
jishan siddique

Reputation: 1895

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

Upvotes: 1

Jigar Sangoi
Jigar Sangoi

Reputation: 159

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
}

Upvotes: 1

Related Questions