[英]How to handle a strongly typed modal in a strongly typed view with different types
我正在使用模式登錄和注冊用戶。 每個模式都是強類型的,以利用ASP.NET內置帳戶類( RegisterModel
和LoginModel
)。 但是,由於調用這些模式的兩個按鈕位於導航欄上,並且導航欄位於每個頁面上,因此我收到錯誤消息,因為大多數視圖都是強類型的,因此無法處理局部視圖(模式)以使用其他強類型模型。
在強類型環境中如何處理強類型模態?
_布局:
<body>
<div class="navbar">
@Html.Partial("_LoginPartial") // contains buttons to call login/register modals
</div>
<div>
@Html.Partial("_LoginModal")
@Html.Partial("_RegisterModal")
</div>
<div class="container">
@Html.RenderBody()
</div>
</body>
/新聞/索引:
@model List<NewsBulletinViewModel>
LoginModal:
@model NoName.Models.LoginModel
相關說明:由於我的模態中有表單,當發生驗證錯誤時,如何引用這些模態? 理想情況下,模態應該再次彈出(或永遠不要關閉),並顯示驗證錯誤。
@Html.Partial
中有一個重載,該重載使用一個對象,用於部分頁面的Model。 如果在布局中包括“部分”,則在每個頁面中,都需要一種邏輯來保留該數據。 例如,如果您使用LoginModel
和RegisterModel
,則可以執行以下操作:
@Html.Partial("_LoginPartial", ViewBag.LoginModel ?? new LoginModel())
@Html.Partial("_RegisterPartial", ViewBag.RegisterModel ?? new RegisterModel())
並將執行LoginModel
(或RegisterModel
)的角色留給執行控制器。 如果ViewBag
沒有任何ViewBag
,它將回ViewBag
創建一個空的內容。
編輯:根據其他信息,我將為LoginPartial
( RegisterPartial
是相同的邏輯)執行此操作:
public class AccountController : Controller
{
public ActionResult LoginPartial()
{
return PartialView("_LoginPartial", (Session["Login"] as LoginModel) ?? new LoginModel());
}
[HttpPost]
public HttpStatusCodeResult SaveLoginModel(LoginModel model)
{
Session["Login"] = model;
return new HttpStatusCodeResult(200);
}
}
然后,在_LoginPartial
,執行所需的操作,但是添加一個javascript代碼,以在值更改時將ajax發布請求發送到控制器的SaveLoginModel
操作,以使模型保持同步(有關如何執行操作,有很多信息那)。
現在,不要做:
@Html.Partial("_LoginPartial", ViewBag.LoginModel ?? new LoginModel())
@Html.Partial("_RegisterPartial", ViewBag.RegisterModel ?? new RegisterModel())
您可以這樣做:
@Html.Action("LoginPartial", "AccountController");
@Html.Action("RegisterPartial", "AccountController");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.