2016-04-07 41 views
0

在Umbraco中,我可以将MVC偏分量与SurfaceController挂钩,在回发后重新呈现时丢失模型状态,或者过早验证模型,并在@Html.ValidationMessageFor助手上显示验证错误最初的页面渲染。我真正想要的是符合vanilla MVC partials和models的行为。Umbraco SurfaceController模型状态/模型验证问题

我创建MVC谐音为一把umbraco使用由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项目中的有效模型属性。

任何想法,我可能是做错了?

回答

0

我通过调用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,未来可能不需要此解决方法。