0

我正在使用模式登录和注册用户。每个模式都是强类型的,以利用 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>

登录模式:

@model NoName.Models.LoginModel

在相关说明中:由于我的模态中有表单,当发生验证错误时,我如何参考这些模态?理想情况下,模式应该再次弹出(或永远不会关闭)并显示验证错误。

4

1 回答 1

1

有一个重载@Html.Partial需要一个对象,用于部分页面的模型。如果您在布局中包含 Partial,则在每个页面中,您都需要一个逻辑来保留该数据。例如,如果您采用LoginModeland RegisterModel,您可以这样做:

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

并留给执行控制器放置LoginModel(或RegisterModel)的角色。如果 中没有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");
于 2013-06-29T19:08:37.200 回答