带有返回Json返回空白页面的ajax

问题描述 投票:2回答:1

**嗨,我在一个视图中具有“登录和注册页面”。登录控制器没有视图。当用户输入错误的电子邮件和密码时,我想显示错误消息。但它返回带有URL帐户/登录名的{“ Fail”}的空白页

$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").on("click",function () {
    //collect the user data
    var data = {};
    data.Email = $("#Email").val();
    data.Password = $("#Password").val();
    var token = $('input[name="__RequestVerificationToken"]').val();

    $.ajax({
        contentType: "application/json; charset=utf-8",
        url: "/Account/Login",
        type: "POST",
        dataType: "json",
        data: {
            model: data,
            __RequestVerificationToken: token,

        },
        success: function () {

                $("#alertmessage").show()


        },

        })
    })
})

 <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>
[HttpGet]
    public ActionResult Login()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(string Emaillog,string Passwordlog)
    {

        string result = "Fail";

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

        if (appUser != null)
        {
            if (appUser.Password ==Passwordlog)
            {
                Session["ActiveUser"] = appUser;
                return RedirectToAction("MainAccount");
            }
            }
        return Json(result, JsonRequestBehavior.AllowGet);    }

我尝试更改JsonResult操作,但仍然相同。我不知道哪里出了问题。 **

ajax asp.net-mvc model-view-controller
1个回答
0
投票

由于您的提交按钮正在提交表单并进行重定向,因此未调用您的ajax调用。

添加event.preventDefault()按钮单击事件,使其不会执行常规的同步POST。

// add e parameter, this is for the event
$("#logbut").on("click",function (e) {
    // this is to avoid the form being submitted, and proceed with your script call
    e.preventDefault();

    // ...
})
© www.soinside.com 2019 - 2024. All rights reserved.