简体   繁体   English

如何将数据从Action传递到mvc4中的Ajax成功函数?

[英]How to pass data from Action to Ajax success function in mvc4?

hi i am want to when login succesfully then call my success function otherwise call error function 您好,我想成功登录后再调用我的成功函数,否则调用错误函数

View code here 在这里查看代码

<div class="container">
<div class="login-container">
    <div class="avatar"><img src="@Url.Content("~/Content/images/download.jpeg")" style="max-width:95%;" /></div>
    <div class="form-box">
        @using (Html.BeginForm())
        {
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                @Html.TextBoxFor(m => m.UserId, new { @class = "form-control", @id="userid", @placeholder = "Username", @required = "required", @maxlength = "20" })
            </div>
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                @Html.PasswordFor(m => m.Password, new { @class = "form-control", @id = "userpass", @placeholder = "Password", @required = "required", @maxlength = "20" })
            </div>
            <button class="btn btn-info btn-block login" type="submit" id="login-btn"><i class="glyphicon glyphicon-log-in"></i>&nbsp;&nbsp;&nbsp;Login</button>
        }
    </div>
</div>

ajax code here: 这里的ajax代码:

<script>
$(document).ready(function () {
    $('#login-btn').click(function () {
        var dataObject = {
            Id: $("#userid").val(),
            Password: $("#userpass").val()
        };
        $.ajax({
            url: '@Url.Action("Login","Account")',
            type: "POST",
            data: dataObject,
            dataType: "json",
            success: function (data) {

                if (data.toString() == "login") {
                    toastr['success']("Login Successfully");
                }
                else if (data.toString() == "error") {
                    toastr['error']("Id or Password is incorrect");
                }
            },
            error: function () {
                toastr['error']("Hello");
            }
        });

    });
});

Controller Code here: 控制器代码在这里:

[HttpPost]
    public ActionResult Login(LoginMaster model)
    {
        string message = "";
        if (ModelState.IsValid)
        {
            try
            {
                var user = from emp in db.LoginMasters
                           where emp.UserId == model.UserId && emp.Password == model.Password
                           select emp;

                var rol = user.FirstOrDefault();
                if (rol != null)
                {
                    var realrol = rol.Role;
                    if (realrol == "admin")
                    {
                        message = "login";
                        return RedirectToAction("Index", "Home");
                    }
                    else if (realrol == "user")
                    {
                        Session["userid"] = rol.UserId;
                        message = "login";
                        return RedirectToAction("User", "Home");
                    }
                }
                else
                {
                    message = "error";
                }
            }
            catch (Exception ex)
            {
                ViewBag.cath = ex.Message;
            }

        }
        else
        {
            message = "error";
        }
        if (Request.IsAjaxRequest())
        {
            return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        return View();

i am want to when we login succesfully that time call this 我想当我们成功登录的时候叫这个

toastr['success']("Login Successfully");

and when login fail that time call 当登录失败时

toastr['error']("Id or Password is incorrect");

please solve this problem. 请解决这个问题。 thanks in advance! 提前致谢!

Assuming your controller code hits the part that returns the json then you can access it via .Data : 假设您的控制器代码命中了返回json的部分,那么您可以通过.Data访问它:

success: function (data) {

            if (data.Data == "login") {
                toastr['success']("Login Successfully");
            }
            else if (data.Data == "error") {
                toastr['error']("Id or Password is incorrect");
            }
        }

You set the .Data property within your code here: 您可以在此处的代码中设置.Data属性:

new JsonResult { Data = message ...

and the problem with your success call is that it is testing the entire json object, not the .Data property. 成功调用的问题在于它正在测试整个json对象, 而不是 .Data属性。

data.toString() == "login"

no sir our problem is our Action where we can put hit point that is not run in a sequence our this point is firstly execute 不,先生,我们的问题是我们的行动,我们可以放置未按顺序运行的生命值,这一点首先执行

if (Request.IsAjaxRequest())
    {
        return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

then after execute this part 然后执行此部分

try
        {
            var user = from emp in db.LoginMasters
                       where emp.UserId == model.UserId && emp.Password == model.Password
                       select emp;

            var rol = user.FirstOrDefault();
            if (rol != null)
            {
                var realrol = rol.Role;
                if (realrol == "admin")
                {
                    message = "login";
                    return RedirectToAction("Index", "Home");
                }
                else if (realrol == "user")
                {
                    Session["userid"] = rol.UserId;
                    message = "login";
                    return RedirectToAction("User", "Home");
                }
            }
            else
            {
                message = "error";
            }
        }
        catch (Exception ex)
        {
            ViewBag.cath = ex.Message;
        }

so problem is we can not set correct string in message variable so please first of all you can make a sample in js fiddle then provide me link 所以问题是我们无法在message变量中设置正确的字符串,因此请首先在js小提琴中制作一个示例,然后提供我的链接

As you have used this code in your script. 在脚本中使用此代码后。 :

var dataObject = {
            Id: $("#userid").val(),
            Password: $("#userpass").val()
        };

if your LoginMaster model contains Id & Password it'll display data. 如果您的LoginMaster模型包含IdPassword它将显示数据。 If you have UserId & Password then you have to change your code in script like below. 如果您具有UserIdPassword则必须在脚本中更改代码,如下所示。

 var dataObject = {
                UserId: $("#userid").val(),
                Password: $("#userpass").val()
            };

In short replace Id with UserId . 简而言之,将Id替换为UserId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM