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

时间:2016-04-07 01:07:31

标签: c# asp.net-mvc validation state umbraco7

在Umbraco中,我可以使用SurfaceController连接MVC部分,这些部分在回发后重新渲染时会丢失模型状态,或者过早验证模型,因此会显示@Html.ValidationMessageFor个助手的验证错误初始页面渲染。我真正想要的是与vanilla MVC部分和模型一致的行为。

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

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

部分:

@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")

SurfaceController:

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()

在回发后渲染时,我放松了模型状态。用户编辑丢失。

当我使用时:

[ChildActionOnly]
public ActionResult RegisterDetails(UserModel model)

验证发生得很早,所以我看到验证错误,就好像回发已经发生一样。在代码中设置断点时,我可以看到在访问局部视图之前首先调用SurfaceController代码。在局部视图中填充模型,但由于某种原因,所有验证消息都显示为模型为空。如果我回发帖子,则会保留模型状态,并且所有内容都会按预期显示 - 错误模型属性的验证消息,没有良好模型属性的消息。

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

知道我可能做错了吗?

1 个答案:

答案 0 :(得分:0)

我在需要填充模型时调用[ChildActionOnly] public ActionResult RegisterDetails(UserModel model) { if (model == null || model.Id == Guid.Empty) { model = new UserModel(GetUser()); ModelState.Clear(); } return View(model); } 解决了这个问题,如果模型不存在的话。

{{1}}

但是,将来可能不需要这项工作,因为speculation that this scenario could be a bug in Umbraco 7.4.2