成功登录后重定向ajax

时间:2012-11-03 00:05:29

标签: c# asp.net asp.net-mvc-3 asp.net-ajax

我一直在互联网上试图找出这个。我正在尝试添加一个jquery对话框窗口,该窗口将调用一个操作来登录用户,然后在成功登录后,将用户重定向到他们的配置文件页面,否则保持对话框窗口打开并提示用户输入相应的错误消息。到目前为止,登录部分似乎有效,但当操作返回时,它会使用户保持在同一页面上。我需要做出哪些更改才能确定成功登录和重定向?这是我的代码:

"Javascript code"
$.validator.unobtrusive.parse('#LogOnForm');
$('#LogOnDialog').dialog({
    autoOpen: false, width: 450, height: 300, modal: true,
     buttons: {
        'Log On': function () {
            if ($('#LogOnForm').validate().form()){
                $.ajax({
                    url: '@Url.Action("LogOnPartial", "Account")',
                        type: 'POST',
                        data: $('form').serialize(),
                        datatype: 'json',
                        success: function (result) {
                            $('#LogOnDialog').html(result).dialog('open');
                        }
                    });
                }
            },
            Cancel: function () { 
                $(this).dialog('close'); 
            }
        }
    });




    $('#linkSignIn').live('click', function () {
        $('#LogOnDialog').html('')
        .dialog('option', 'title', 'Sign In')
        .load('@Url.Action("LogOnPartial", "Account")', function () { $('#LogOnDialog').dialog('open'); });
    });



    "Controller Action"
    [HttpPost]
    public ActionResult LogOnPartial(LogOnModel model)
    {
        if (ModelState.IsValid)
        {
            UserPrincipal principal = new UserPrincipal(model.EmailAddress, model.Password);
            HttpContext.User = principal;
            FormsAuthentication.SetAuthCookie(model.EmailAddress, true);
            return PartialView("LogOnPartial", model);
        }

        return PartialView("LogOnPartial", model);
    }

1 个答案:

答案 0 :(得分:2)

我不确定您希望如何实现此目标,但在您的结果中,您很可能希望返回您要登录的个人资料的用户的ID。

   success: function (result) {
                           if(result=='')/// no result show the dialog again 
                            {
                             $('#LogOnDialog').html(result).dialog('open');
                            }
                            else // redirect to profile page 
                            {
                                 window.location = 'profile/'+result;   
                            }
                    }
                });

您的行为可能类似

    public ActionResult ProvinceFilter(LogOnModel model)
    {
      string result=="";    
      UserPrincipal principal = new UserPrincipal(model.EmailAddress, model.Password); //in order to retorn exact error you must modify the principle to check if the user is valid or not and return specific error
     if(principal==null) //or not valid 
      {
         result="Your Username or Password is not correct";
      }
      else
       {
        HttpContext.User = principal;
        FormsAuthentication.SetAuthCookie(model.EmailAddress, true);
        result=principal.UserID.ToString();
       }
        return Json(result);
    }