如何在jQuery $ ajax上获取MVC操作错误消息以显示在页面上

时间:2014-12-10 02:35:45

标签: jquery asp.net-mvc

我有一个页面在右侧显示来自PartialView的登录表单,当用户提交其凭据时,jQuery $ ajax调用控制器中的方法来验证用户是否存在,否则为null。

请指出我做错了什么并帮助我了解我需要更改或添加以使其正常工作,目前我无法看到传递给action方法的userid或密码的值。

我可以看到页面上的消息:"提供的用户名或密码不正确。"但重点是,价值观没有通过。

以下是我的代码的完整示例:

Index.cshtml

<div id="YourOrder_Login">
@if (!User.Identity.IsAuthenticated)
{
    <div class="YourOrder_loginForm">
        <div class="YourOrder_loginArea" style="position:relative;">
            @{Html.RenderAction("ShoppingCartLogin", "ShoppingCart");}
        </div>
    </div>
} else {
    <div class="YourOrder_addressArea" style="position:relative;">
        @{Html.RenderAction("ShoppingCartShippingAddress", "ShoppingCart");}
    </div>
}
</div> 

ShoppingCartLogin(PartialView)

<div class="YourOrder__inputEmail">
<input id="YourOrder_MainLoginEmail" class="YourOrder_MainLoginEmail" name="UserName" type="text" 
tabindex="1" />   
</div>
<div>
<input id="YourOrder_MainLoginPassword" class="YourOrder_MainLoginPassword" name="Password" 
type="password" tabindex="2" />
</div>
<div class="container_btnsignin">
<button type="button" class="fancyButton YourOrder_signin" id="btnLogin" value="SignIn" 
name="Command" onclick="javascript: ShoppingCartLogin();">Sign In</button>

jQuery

<script type="text/javascript">

function ShoppingCartLogin() {

    var userid = $(".YourOrder_MainLoginEmail").val();
    var password = $(".YourOrder_MainLoginPassword").val();
    var url = "/ShoppingCart/ShoppingCartLogin";

    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: JSON.stringify({usr: userid, pwd: password}),//{ userId: userid, pass: password },
        cache: false,
        success: function (result) {
            if (result.success = "Invalid") {
                $('.YourOrder_loginError').css('visibility', 'visible')
                $('.YourOrder_loginError').slideDown().html('The user name or password provided is incorrect.');
            }
            else {
                $('.YourOrder_loginError').css('visibility', 'hidden')
                location.reload();
            }
        }
    });

}

控制器代码

        [HttpPost]
    [AllowAnonymous]
    public ActionResult ShoppingCartLogin(string userId, string pass)
    {
            using (Entities db = new Entities())
            {
                var user = (from u in db.Users where u.Email == userId && u.Password == pass && u.IsActive select u).FirstOrDefault();

                if (user == null)
                {
                    //ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    //return View("ShoppingCartLogin");
                    //return Json(new { status = "success", message = "The user name or password provided is incorrect." }); 
                    return Json(new { error = "Invalid" });
                }


                    List<string> roles = new List<string>();
                    if (user.IsAdmin)
                    {
                        roles.Add("Admin");
                    }
                    if (user.IsOrdersAdmin)
                    {
                        roles.Add("Orders");
                    }
                    if (user.IsStoreAdmin)
                    {
                        roles.Add("Stores");
                    }

                    user.LastLoginDate = DateTime.Now;
                    db.SaveChanges();

                    FormsAuthentication.SetAuthCookie(user.ID.ToString(), true);
                    return View("ShoppingCartShippingAddress");

            }
        }

2 个答案:

答案 0 :(得分:2)

您的参数名称必须匹配,因此您的json对象可能是这样的:{userId:userid,pass:password}

但是,在此方案中使用ajax调用登录不是正确的方法,因为您需要重新加载整个页面以使用ShoppingCartShoppingAddress partialview更新页面。使用表单提交会更容易。

答案 1 :(得分:1)

你在这里做错了两件事。

1.参数不匹配 2.data:Json.Stringify

试试这段代码

<script type="text/javascript">



function ShoppingCartLogin() {

        var userid = "12";
        var password = "Hsakarp";
        var UrlP = "/Default/ShoppingCartLogin";

        $.ajax({
        cache: false,
        type: "POST",
        url: UrlP,
        data: { userId: userid, pass: password },
             success: function (data) {
                 $('#Load').html(data);
             },
             error: function (xhr, ajaxOptions, thrownError) {
                 alert('Error');
             }
     });
}
    }
</script>

--- HTML -

<button id="call" onclick="ShoppingCartLogin()">Post Data</button>

<div id="Load"></div>

- SC -

<h2>ShoppingCartLogin</h2>

<h2>Hrllo from shopping cart</h2>


<h2>Hrllo from shopping cart</h2>

<h2>Hrllo from shopping cart</h2>

- 控制器 -

public ActionResult ShoppingCartLogin(string userId, string pass)
        {

            return View("ShoppingCartLogin");

        }