Umbraco SurfaceController 模型状态/模型验证问题

Umbraco SurfaceController model state / model validation issues

在 Umbraco 中,我可以将 MVC 部分与 SurfaceController 挂钩,在 post 返回后重新渲染时丢失模型状态,或者过早地验证模型并因此显示验证错误 @Html.ValidationMessageFor 初始页面渲染的助手。我真正想要的是与香草 MVC 部分和模型一致的行为。

我正在创建用于 Umbraco 的 MVC 部分,由 SurfaceController 支持以处理渲染和 post-back。

然后我将这些部分包装在 "Macros" 中,这样它们就可以与其他内容一起放入页面内容中,而不是为每个需要的特殊页面创建一个特殊的文档类型(会有很多)。

部分:

@using SomeProject.Web.Controllers
@model SomeProject.Web.Models.Identity.UserModel

@using (Html.BeginUmbracoForm<IdentitySurfaceController>("RegisterDetailsSubmit", null, new { @class = "form-horizontal" }))
{
    @Html.AntiForgeryToken()

    @Html.EditorFor(model => Model)

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-primary" value="Register" />
        </div>
    </div>
}

宏:

@inherits Umbraco.Web.Macros.PartialViewMacroPage
@Html.Action("RegisterDetails", "IdentitySurface")

表面控制器:

using SomeProject.Web.Models.Identity;
using System;
using System.Web.Mvc;

namespace SomeProject.Web.Controllers
{
    public class IdentitySurfaceController : Umbraco.Web.Mvc.SurfaceController
    {

        [ChildActionOnly]
        public ActionResult RegisterDetails(UserModel model)
        {
            if (model == null || model.Id == Guid.Empty) model = new UserModel(GetUser());

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RegisterDetailsSubmit(UserModel model)
        {
            if (ModelState.IsValid)
            {
                ...
            }

            return CurrentUmbracoPage();
        }

    }
}

当我使用:

[ChildActionOnly]
public ActionResult RegisterDetails()

我在 post 返回后渲染时松开模型状态。用户编辑丢失。

当我使用:

[ChildActionOnly]
public ActionResult RegisterDetails(UserModel model)

验证发生得早,所以我到处都看到验证错误,就好像 post 返回已经发生了。在代码中设置断点时,我可以看到在点击局部视图之前先调用 SurfaceController 代码。在部分视图中,模型已填充,但由于某种原因,所有验证消息都显示为模型为空。如果我执行 post 返回,模型状态将被保留并且一切都按预期显示 - 错误模型属性的验证消息,良好模型属性没有消息。

我看到了所有 @Html.ValidationMessageFor 项的验证消息,以及伴随它们的所有 @Html.EditorFor 项的有效模型属性。

知道我做错了什么吗?

当我们需要填充模型(如果模型不存在)时,我通过调用 ModelState.Clear() 解决了这个问题。

[ChildActionOnly]
public ActionResult RegisterDetails(UserModel model)
{
    if (model == null || model.Id == Guid.Empty)
    {
        model = new UserModel(GetUser());
        ModelState.Clear();
    }

    return View(model);
}

但是,由于存在 speculation that this scenario could be a bug in Umbraco 7.4.2

,将来可能不需要此解决方法