0

タイトルの通り、初回は毎回ログインできないのですが、2回目以降はログインできるのですが、どこが悪いのでしょうか?または、コードを実装する新しい方法はありますか? 私はそれに慣れていませんが、それは私にとって学習経験としても役立ちます:)

また、Razor で Url.Action を Object の代わりに文字列 url にする方法はありますか?

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経由でログインすることはお勧めしませんが、あなたの場合、問題はキャッシュが原因である可能性があります。cache : false現在のjqueryajaxリクエストにオプションを追加すると、問題が解決されます。

例 :

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