0

As mentioned in the title, i cannot login everytime for the first time, but subsequent time I can login, where is wrong?Any Help will be appreciated! Or any new ways to implement the code? I'm new to it, it will also serve as a learning experience to me :)

Also is there any way in Razor to make Url.Action to string url instead of Object?

jQuery Client Side:
//To be submitted to the server for authentication
<script>
    $(".btn").click(function () {
        login();
    });
    function login() {
        var username = $("#username").val();
        var password = $("#password").val();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            //url: "/member_control.asmx/Login",
            url: '@Url.Action("Index", "Home")',
            dataType: 'json',
            data: '{"username": "' + username + '","password": "' + password + '" }',

            success: function(result) {
                if (result.Success) {
                    window.location.href = result.redirectToUrl;
                } else {
                    alert(result.Message);
                }
            }
        });
    }
</script>


       Json Server Side:  
        //json will be returning back to the jquery request

            [AllowAnonymous]
            [HttpPost]
             public JsonResult Index(LoginModel1 model, Object redirectToUrl){
            //set default
            redirectToUrl = Url.Action("Test", "Home");

            if (ModelState.IsValid)
            {
                if (DataAccess.DAL.UserIsValid(model.Username, model.Password))//Authentication
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    return Json(new { Success = true, redirectToUrl = Url.Action("Test", "Home") });
                }
                {
                    return Json(new { Success = false, Message = "Login failed, invalid username or password." });
                }
            }
            return Json(new { Success = false, Message = "Login failed" });
    }
4

1 回答 1

0

好吧,不建议通过 ajax 登录,但在您的情况下,问题可能是因为缓存。在您当前的 jquery ajax 请求中添加一个选项cache : false,问题将得到解决。

例子 :

 $.ajax({
    cache : false,
    // existing stuff
 });
于 2012-10-22T16:59:43.960 回答