(2012 年 9 月 14 日更新)
这是我的控制器:
<HttpPost()> _
Public Function Login(ByVal viewmodel As LoginViewModel) As ActionResult
Dim result As New LoginResponse()
Try
Dim objUserCredentialsType As UserCredentialsType = UserProfileType.Login(viewmodel.UserName, viewmodel.Password, 0, CStr(AppSettings("softwareLicense")))
'store user credentials in session
HttpContext.Session.Add("_CurrentUserCredentials", objUserCredentialsType)
FormsAuthentication.SetAuthCookie(viewmodel.UserName, viewmodel.RememberMe)
result.Status = "Success"
result.ReturnUrl = "~/Account/Welcome"
Return Json(result)
Catch ex As Exception
result.Status = "Failed"
result.Errors.Add(ExceptionWrapper.Wrap(ex).ExceptionMessage())
Return Json(result)
End Try
End Function
Public Class LoginResponse
Public Property Status() As String
Get
Return m_Status
End Get
Set(value As String)
m_Status = Value
End Set
End Property
Private m_Status As String
Public Property Errors() As List(Of String)
Get
Return m_Errors
End Get
Set(value As List(Of String))
m_Errors = Value
End Set
End Property
Private m_Errors As List(Of String)
Public Property ReturnUrl() As String
Get
Return m_ReturnUrl
End Get
Set(value As String)
m_ReturnUrl = value
End Set
End Property
Private m_ReturnUrl As String
Public Sub New()
Errors = New List(Of String)()
End Sub
End Class
这是我的看法:
<section id="login">
<div id="login-form-container" class="span6">
@Using (Ajax.BeginForm("Login", "Account", Nothing, New AjaxOptions With {.HttpMethod = "post", .OnBegin = "LoginFormAjaxValidate"}, New With {.id = "login-form"}))
@<fieldset>
<legend>Log in to your account now</legend>
<div class="row-fluid">
<div class="span12">
@Html.LabelFor(Function(m) m.UserName)
@Html.TextBoxFor(Function(m) m.UserName, New With {.class = "span12", .placeholder = "Username"})
@Html.ValidationMessageFor(Function(m) m.UserName)
</div>
</div>
<div class="row-fluid">
<div class="span12">
<label for="Password">Your password</label>
@Html.PasswordFor(Function(m) m.Password, New With {.class = "span12", .placeholder = "Password", .type = "password"})
@Html.ValidationMessageFor(Function(m) m.Password)
</div>
</div>
<div class="row-fluid">
<div class="span12">
<label for="RememberMe" class="checkbox clearfix">
@Html.CheckBoxFor(Function(m) m.RememberMe)
Remember me next time I visit
</label>
</div>
</div>
<button id="login-submit" type="submit" class="btn btn-primary input-small" value="submit">Log in</button>
</fieldset>
End Using
</div>
</section>
这是视图底部的脚本:
<script type="text/javascript">
function LoginFormAjaxValidate() {
$("#login-form").serialize(), function (r) {
if (r.Status == "Success") {
top.location.href = "@Url.Content("~/Account/Welcome")";
}
else {
//Lets get the Errors from our JSON
$.each(r.Errors, function (index, item) {
alert(r.item);
});
}
}
}
</script>