Ajax.BeginForm返回PartialView代码不会更新

时间:2015-04-07 10:55:06

标签: asp.net-mvc asp.net-mvc-4 asp.net-ajax partial-views

我正在使用Ajax partial执行登录注销功能。为此我有一个View来检查用户是否登录,并相应地显示登录或注销表单。 在提交时,它会执行ajax请求并登录或注销用户。在控制器中执行此操作后,返回相同的局部视图。

因此预期的行为是返回局部视图必须再次检查登录状态并相应地刷新视图,而是加载相同的表单。

部分视图:

@model Models.LoginModel


@if (Member.MemberIsLoggedOn())
{
    using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "login-form-update",
},new {
    @class="loginform form"
}))
    {

    <div class="col-md-12 padding-zero">
        <div class="row flt-right">
            Hello @Context.User.Identity.Name,  <input type="submit" name="logout" class="btn btn-default" value="Log Out" />
        </div>
    </div>

    }
}
else
{

    using (Ajax.BeginForm("LoginForm", "Account", null, new AjaxOptions
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "login-form-update",
}, new {
    @class = "loginform form"
}))
    {

    <div class="col-md-12 padding-zero">
        <div class="row flt-right">
            <div class="form-group col-md-5">
                @Html.TextBoxFor(x => Model.Username, new { @class = "form-control", @placeholder = "Username" })
            </div>
            <div class="form-group col-md-5">
                @Html.TextBoxFor(x => Model.Password, new { @class = "form-control", @placeholder = "Password", @type = "Password" })
            </div>
            <div class="form-group col-md-2 flt-right">
                <input type="submit" name="login" class="btn btn-default" value="Go" />
            </div>
        </div>
    </div>
    }
}

控制器:

public class AccountController : Controller
    {
        [HttpPost]
        public ActionResult LoginForm(LoginModel model)
        {

            if (!ModelState.IsValid)
            {

                //Do nothing
            }

            // Login
            if (Membership.ValidateUser(model.Username, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
                return PartialView("Header/LoginForm", new Models.LoginModel());
            }
            else
            {
                ModelState.AddModelError("Username", "Username is not valid");
                //do nothing
            }
        }

        public ActionResult Logout()
        {

            FormsAuthentication.SignOut();
            Session.Clear();
            return PartialView("Header/LoginForm", new Models.LoginModel());
        }

    }

现在我的问题是登录/注销正常发生,但是除非刷新页面,否则更改不会反映,我想通过Ajax.BeginForm()来避免,

更新 如果我点击两次视图更改,但这不是一个很好的用户体验。

1 个答案:

答案 0 :(得分:2)

我认为这可能是由于缓存问题造成的。您需要使用输出缓存属性来禁用该操作方法的缓存。 你可以使用这样的东西。

 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")] 

在返回之前还要清除ModelState。

 ModelState.Clear();
 return PartialView(model); 
相关问题