部分视图和ajax

时间:2012-01-16 23:42:09

标签: ajax asp.net-mvc-3

我想通过ajax更新部分视图,但它不起作用。看看这个模型类:

   public class LogOnModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }

        public bool IsLoggedIn { get; set; }

        public string ReturnUrl { get; set; }
    }

以下观点:

@model ITW2012Mobile.ViewModels.LogOnModel
<div id='LogOn' style="background-color: White;">
    @using (Ajax.BeginForm("LogOnAjax", "Home", new AjaxOptions { UpdateTargetId = "LogOn", OnSuccess = "logInComplete" }))
    { 
        ITW2012Mobile.ViewModels.LogOnModel m = Model;
        @Html.EditorFor(model => model.IsLoggedIn)
        @Html.EditorFor(model => model.ReturnUrl)
        <div>
            @Html.ValidationSummary()
        </div>
        <div>
            @Html.LabelFor(model => model.UserName)
            @Html.EditorFor(model => model.UserName)
        </div>
        <div>
            @Html.LabelFor(model => model.Password)
            @Html.EditorFor(model => model.Password)
        </div>
        <div>
            <input type="submit" value="Login" />
        </div>
    }
</div>

和以下控制器类:

public ActionResult LogOnAjax(LogOnModel model)
{
    if (!User.Identity.IsAuthenticated)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                model.IsLoggedIn = true;
                model.ReturnUrl = Url.Action("Index", "Home"); 
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return PartialView("PartialViewAjaxLogOn", model);
    }
    else
    {
        return PartialView("PartialViewLogOut");
    }
}

即使用户名/密码正确且IsLoggedIn = true且ReturnUrl!=空视图显示这些变量的空字段(但调试器显示其中的值)。为什么以及如何正确使用它?

1 个答案:

答案 0 :(得分:0)

尝试从模型状态清除您在操作中修改的值,或者如果您在html帮助程序中使用它们,则将使用旧值:

ModelState.Remove("IsLoggedIn");
model.IsLoggedIn = true;
ModelState.Remove("ReturnUrl");
model.ReturnUrl = Url.Action("Index", "Home"); 

另外请记住,在成功进行身份验证和cookie发布后,您不应显示视图(部分在您的情况下)。您应该重定向,以便客户端在后续请求中发送身份验证cookie。您应该重定向到返回网址。但是,由于您使用AJAX执行此操作,您应该向客户端发送一些指示认证成功,以便您可以在客户端上重定向。