我的任務是在一個視圖上創建登錄和註冊表單!在一個視圖上的登錄和註冊表單MVC3 Razor
我有家的感覺。在主頁上我有兩種形式,登錄和註冊。他們通過@ Html.RenderPartial(部分視圖名稱,模型)進行渲染。這種形式與帳戶控制器(登錄和註冊操作)相關。
讓我先爲您提供一些代碼...
模式:
// Login model, that contains email and password
public class Login
{
…
}
// Registration model that contains minimum user data, e.g. name, surname
public class Register
{
...
}
// Model for home view which contains models for both register and login
public class Home
{
public Login LoginModel { get; set; }
public Register RegisterModel { get; set; }
}
瀏覽: Index.cshtml
@model App.Models.Home.Home
<!-- Login Box -->
@{ Html.RenderPartial("_LoginArea", Model.LoginModel); }
<!-- Register Box -->
@{ Html.RenderPartial("_RegisterArea", Model.RegisterModel); }
_LoginArea.cshtml
@model App.Models.Account.Login
<div style="float: left; margin-right: 100px;">
<h1>@Localization.Account.Login</h1>
<!-- Login form -->
<div id="loginBox">
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div class="editor-label">
@Html.LabelFor(m => m.Email):
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password):
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="@Localization.Account.Login" />
</p>
}
</div>
</div>
_RegisterArea.cshtml
@model App.Models.Account.Register
<div style="vertical-align: bottom;">
<h1>@Localization.Account.Register</h1>
<div>
@using (Html.BeginForm("Register", "Account"))
{
//same things like in login
}
...
控制器:
的HomeController
//
// GET: /Home/
public ActionResult Index(Home model)
{
//
// If logedin redirect to profile page
// Else show home page view
//
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "User", new { id = HttpContext.User.Identity.Name });
}
else
{
model.LoginModel = new Login();
model.RegisterModel = new Register();
return View(model);
}
}
只需出示您的帳戶控制器登錄行動
//
// POST: /Account/Login
[HttpPost]
public ActionResult LogIn(Login model)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "User", new { id = HttpContext.User.Identity.Name });
}
else
{
if (ModelState.IsValid)
{
if (model.ProcessLogin())
{
return RedirectToAction("Index", "User", new { id = HttpContext.Session["id"] });
}
}
}
//Note: this is problem part
// If we got this far, something failed, redisplay form
return View("~/Views/Home/Index.cshtml", model);
}
所以一切正常,但是!當模型狀態無效我有以下異常
The model item passed into the dictionary is of type 'App.Models.Account.Login', but this dictionary requires a model item of type App.Models.Home.Home'.
我可以綁定這部分的意見和帳戶行動家居模式,但是這不是我所需要的。 我打算在其他視圖中使用_LoginArea.cshtml視圖(例如在'用戶'視圖的頁面標題中,並且該視圖有另一個模型) 因此,我需要操作方法(例如登錄)來檢索登錄模型,而不是主頁或其他任何東西。但在這種情況下,我無法將模型返回到主視圖。 我該如何解決這個問題?什麼是最合適的方式? 對不起,很多代碼,只是想清楚的事情。