自定义模型绑定器中的数据注释验证

发布于 2024-09-16 22:10:06 字数 3099 浏览 6 评论 0原文

我已经在我的 MVC 项目中为 List 编写了一个自定义模型绑定程序,但是我现在陷入了如何让这个绑定程序根据我的 DataAnnotations 验证属性进行验证的困境。

我在互联网上找到了一些讨论类似场景的帖子,但我无法找到适合我的特定场景的任何内容。

模型绑定器代码:

    public class QuestionModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        List<QuestionEditModel> res = new List<QuestionEditModel>();
        var form = controllerContext.HttpContext.Request.Form;
        int i = 0;
        while (!string.IsNullOrEmpty(form["Questions[" + i + "].QuestionID"]))
        {
            var p = new QuestionEditModel();
            p.QuestionID = form["Questions[" + i + "].QuestionID"];
            p.Answer = form["Questions[" + i + "].Answer"];
            p.AnswerRequired = (form["Questions[" + i + "].AnswerRequired"] == "True") ? true : false;
            p.completedBy = form["Questions[" + i + "].completedBy"];
            p.completedOn=NullableParser.ParseNullableDateTime(form["Questions[" + i + "].CompletedOn"]);
            p.DefaultText = form["Questions[" + i + "].DefaultText"];
            p.EntryType = form["Questions[" + i + "].EntryType"];
            p.HelpText = form["Questions[" + i + "].HelpText"];
            p.OptionRequired = (form["Questions[" + i + "].OptionRequired"] == "True") ? true : false;
            p.OptionValue = NullableParser.ParseNullableInt(form["Questions[" + i + "].OptionValue"]);
            p.QuestionName = form["Questions[" + i + "].QuestionName"];
            p.QuestionText = form["Questions[" + i + "].QuestionText"];
            res.Add(p);
            i++;
        }

        return res;
    }

    private bool HasGenericTypeBase(System.Type type, System.Type genericType)
    {
    while (type != typeof(object))
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
        type = type.BaseType;
    }

    return false;        
    }

}

我的模型元数据:

    [MetadataType(typeof(QuestionEditModelMetaData))]
public partial class QuestionEditModel { }


public class QuestionEditModelMetaData
{
    [Required]
    public string QuestionID { get; set; }
    [Required]
    public string QuestionName { get; set; }
    [Required]
    public string QuestionText { get; set; }
    [Required]
    public string DefaultText { get; set; }
    [Required]
    public string EntryType { get; set; }
    [Required]
    public string HelpText { get; set; }

    public Boolean AnswerRequired { get; set; }
    public Boolean OptionRequired { get; set; }

    //[RequiredIfTrue("AnswerRequired")]
    [Required]
    public string Answer { get; set; }

    [RequiredIfTrue("OptionRequired")]
    public int? OptionValue { get; set; }

    public string completedBy { get; set; }
    public DateTime? completedOn { get; set; }

    public List<Option> options { get; set; }

}

requiredIfTrue 属性来自 MVC 万无一失的验证 库。显然它还不够万无一失!

I have written a custom model binder for List in my MVC project however I am now stuck in how to get this binder to validate against my DataAnnotations validation attributes.

I have found some posts on the interwebs that talk about similar scenarios, but I haven't been able to find anything that works for my particular scenario.

Model Binder Code:

    public class QuestionModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        List<QuestionEditModel> res = new List<QuestionEditModel>();
        var form = controllerContext.HttpContext.Request.Form;
        int i = 0;
        while (!string.IsNullOrEmpty(form["Questions[" + i + "].QuestionID"]))
        {
            var p = new QuestionEditModel();
            p.QuestionID = form["Questions[" + i + "].QuestionID"];
            p.Answer = form["Questions[" + i + "].Answer"];
            p.AnswerRequired = (form["Questions[" + i + "].AnswerRequired"] == "True") ? true : false;
            p.completedBy = form["Questions[" + i + "].completedBy"];
            p.completedOn=NullableParser.ParseNullableDateTime(form["Questions[" + i + "].CompletedOn"]);
            p.DefaultText = form["Questions[" + i + "].DefaultText"];
            p.EntryType = form["Questions[" + i + "].EntryType"];
            p.HelpText = form["Questions[" + i + "].HelpText"];
            p.OptionRequired = (form["Questions[" + i + "].OptionRequired"] == "True") ? true : false;
            p.OptionValue = NullableParser.ParseNullableInt(form["Questions[" + i + "].OptionValue"]);
            p.QuestionName = form["Questions[" + i + "].QuestionName"];
            p.QuestionText = form["Questions[" + i + "].QuestionText"];
            res.Add(p);
            i++;
        }

        return res;
    }

    private bool HasGenericTypeBase(System.Type type, System.Type genericType)
    {
    while (type != typeof(object))
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
        type = type.BaseType;
    }

    return false;        
    }

}

My Model MetaData:

    [MetadataType(typeof(QuestionEditModelMetaData))]
public partial class QuestionEditModel { }


public class QuestionEditModelMetaData
{
    [Required]
    public string QuestionID { get; set; }
    [Required]
    public string QuestionName { get; set; }
    [Required]
    public string QuestionText { get; set; }
    [Required]
    public string DefaultText { get; set; }
    [Required]
    public string EntryType { get; set; }
    [Required]
    public string HelpText { get; set; }

    public Boolean AnswerRequired { get; set; }
    public Boolean OptionRequired { get; set; }

    //[RequiredIfTrue("AnswerRequired")]
    [Required]
    public string Answer { get; set; }

    [RequiredIfTrue("OptionRequired")]
    public int? OptionValue { get; set; }

    public string completedBy { get; set; }
    public DateTime? completedOn { get; set; }

    public List<Option> options { get; set; }

}

The RequiredIfTrue attribute is from the MVC Foolproof Validation library. Apparently it isn't quite foolproof enough!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的往事 2024-09-23 22:10:07

这里的解决方案有效。

自定义模型绑定、模型状态和数据注释

选择让生活变得非常轻松。

The solution from here works.

Custom model binding, model state, and data annotations

The CreateModel option makes life really easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文