我有一个登录表单显示在我的mvc网站的所有页面上,要求用户登录或向他们显示欢迎消息,如果他们已经登录了各种帐户详细信息(公司徽标等),我没有登录页面本身所有登录都是通过这个“小部件”
来处理的为了实现这一点,到目前为止,我有以下内容
在我的主要版面
<div id="top_right">
@{ Html.Partial("_LogOnPartial");}
</div>
_LogOnPartial.cshtml
@if (Request.IsAuthenticated)
{
// TODO: show company logo
Html.RenderAction("Details", "Account");
}
else
{
Html.RenderAction("LogOn", "Account");
}
帐户控制器
public class AccountController : Controller
{
public PartialViewResult LogOn()
{
return PartialView();
}
[HttpPost]
public ActionResult LogOn(LogOnModel userDetails, string returnUrl)
{
//TODO: validate user here
if(ModelState.IsValid)
{
if(Membership.ValidateUser(userDetails.UserName, userDetails.Password))
{
FormsAuthentication.SetAuthCookie(userDetails.UserName, userDetails.RememberMe);
return Redirect(returnUrl);
}
else
{
ModelState.AddModelError("", "The username or password provided was incorrect");
}
}
return PartialView(userDetails);
}
public PartialViewResult Details()
{
//TODO: query membership for user information
var user = new UserDetailsViewModel();
return PartialView(user);
}
}
}
LogOn.cshtml
@model LogOnModel
<div id="login">
@Html.ValidationSummary()
<h2>Start by Loggin in</h2>
@using (Html.BeginForm("LogOn", "Account"))
{
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<table width="100%" border="0" cellspacing="0" cellpadding="5">
<tr>
<td>
<span class="bluey">Username:</span><br />
@Html.TextBoxFor(m => m.UserName,new {tabindex="1", Class = "field"})
@Html.ValidationMessageFor(m => m.UserName, "*")
</td>
<td>
<span class="bluey">Password:</span><br />
@Html.TextBoxFor(m => m.Password, new {tabindex = "2", Class="field"})
@Html.ValidationMessageFor(m=> m.Password, "*")
</td>
</tr>
<tr>
<td>
<input name="login" type="submit" value="Submit" class="input_btn" tabindex="3" />
</td>
<td>@Html.CheckBoxFor(m=>m.RememberMe) @Html.LabelFor(m=> m.RememberMe) <span class="bluey"> | </span> @Html.ActionLink("Forgot Password?", "Password", "User")></td>
</tr>
</table>
}
</div>
我已经阅读了几篇文章,看来我需要更改我的LogOn.cshtml以使用jquery做一个帖子做/ Account / LogOn动作方法,然后更新div成功或失败的html
我已经看到它使用自定义RenderPartialViewToString完成,但是有人还建议从Action返回Partial就足够了,这将通过jquery代码正确处理,替换div(或新的html。
我还看到一个返回Json(模型)的示例,但我不确定是否会返回实际视图或仅返回编码为json的模型数据
这两种方法都可行吗?或者有更好的方法吗?