我正在做一个使用Ajax partial的登录注销功能。为此,我有一个View来检查用户是否已登录,并相应地显示登录或注销表单。 提交时,会执行ajax请求并登录或注销用户。在控制器中这样做之后,我返回相同的局部视图。Ajax.BeginForm返回PartialView代码不更新
所以预期的行为是在返回部分视图必须再次检查登录状态并相应地刷新视图,而是加载相同的形式。
管窥:
@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(),
更新 如果我点击两次视图更改,但这不是良好的用户体验。
你设置'UpdateTargetId =“登录形式更新”',但有没有与任何元素'ID =“登录形式更新”'在HTML? – ekad
是的,它是在局部视图外,我登录和注销后尝试了两个不同的局部视图,这在某种程度上起作用,但仍然没有在刷新之前获得'@ Context.User.Identity.Name'。 –
尝试激活Firebug并在登录或注销后查看是否有任何错误。 – ekad