【问题标题】:Umbraco cannot AddModelError during HttpPost in SurfaceController在 SurfaceController 中的 HttpPost 期间,Umbraco 无法 AddModelError
【发布时间】:2016-04-07 04:31:45
【问题描述】:

在表单回发期间验证 Umbraco SurfaceController 中的模型时,我无法使用 ModelState.AddModelError 添加验证错误消息以向用户提供反馈。任何想法为什么?

我可以毫无问题地在[ChildActionOnly] 渲染方法中使用ModelState.AddModelError

[ChildActionOnly]
public ActionResult VerifyEmail(VerifyEmailModel model)
{
    // This DOES work
    ModelState.AddModelError("SomeProperty", "Some error message to display.");

    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyEmailSubmit(VerifyEmailModel model)
{
    // This DOESN'T work
    ModelState.AddModelError("SomeProperty", "Some error message to display.");

    return CurrentUmbracoPage();
}

任何想法如何解决这个问题?

我想我可以尝试编写自定义代码 System.ComponentModel.DataAnnotations.ValidationAttribute,但我需要做的验证需要根据其他模型属性查找数据,因此开始变得有点复杂。

【问题讨论】:

标签: c# validation model umbraco umbraco7


【解决方案1】:

我采用了自定义System.ComponentModel.DataAnnotations.ValidationAttribute 的编码来解决此问题:

public class VerificationCodeAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string code = (string)value;
        Guid userId = Guid.Empty;

        PropertyInfo userIdProperty = validationContext.ObjectType.GetProperty("UserId");
        if (userIdProperty != null)
            userId = (Guid)userIdProperty.GetValue(validationContext.ObjectInstance);

        // See if we're confirming email via link
        if (userId == Guid.Empty)
            userId = MyProject.Identity.Client.GetUser().Id;

        if (!string.IsNullOrWhiteSpace(code) && !MyProject.Identity.Client.VerifyUserEmail(userId, code))
            return new ValidationResult("Invalid email verification code.");

        return null; // Default for empty string
    }
}

但是,由于有 speculation that this scenario could be a bug in Umbraco 7.4.2,因此将来可能不需要此解决方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多