繁体   English   中英

如何在具有不同类型的强类型视图中处理强类型模态

[英]How to handle a strongly typed modal in a strongly typed view with different types

我正在使用模式登录和注册用户。 每个模式都是强类型的,以利用ASP.NET内置帐户类( RegisterModelLoginModel )。 但是,由于调用这些模式的两个按钮位于导航栏上,并且导航栏位于每个页面上,因此我收到错误消息,因为大多数视图都是强类型的,因此无法处理局部视图(模式)以使用其他强类型模型。

在强类型环境中如何处理强类型模态?

_布局:

<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。 如果在布局中包括“部分”,则在每个页面中,都需要一种逻辑来保留该数据。 例如,如果您使用LoginModelRegisterModel ,则可以执行以下操作:

@Html.Partial("_LoginPartial", ViewBag.LoginModel ?? new LoginModel())
@Html.Partial("_RegisterPartial", ViewBag.RegisterModel ?? new RegisterModel())

并将执行LoginModel (或RegisterModel )的角色留给执行控制器。 如果ViewBag没有任何ViewBag ,它将回ViewBag创建一个空的内容。

编辑:根据其他信息,我将为LoginPartialRegisterPartial是相同的逻辑)执行此操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM