在SurfaceController

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

标签: c# validation model umbraco umbraco7

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

我可以在ModelState.AddModelError渲染方法中使用[ChildActionOnly]而不会出现问题。

[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,但我需要做的验证需要根据其他模型属性查找数据,所以开始变得有点复杂。

1 个答案:

答案 0 :(得分:0)

我使用自定义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