c# - 根据用户未输入的数据验证模型

标签 c# asp.net-mvc automapper validation

我有这个 ViewModel(简化):

public class ResponseViewModel {

    public QuestionViewModel Question { get; set; }
    public string Answer { get; set; }
}

public class QuestionViewModel {

    public string Text { get; set; }
    public string Description { get; set; }
    public bool IsRequired { get; set; }
}

QuestionViewModel 是从我的 DAL 实体 Question 映射而来的,这是一个直接映射自:

public class Question {

    public int Id { get; set; }
    public string Text { get; set; }
    public string Description { get; set; }
    public bool IsRequired { get; set; }
}

如果 Question.IsRequired 为真,我希望能够使 Answer 成为必需的。 然而在回发之后 Only 属性 Answer 被填充(当然)。

去这里最好的方法是什么?我希望能够创建一个验证属性,但不知道如何实现。

更新:

我试图通过使用 ModelBinding 使其工作,但直到现在都没有成功。我做了什么:

public class EntityModelBinder : DefaultModelBinder
  protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        // IF I DO IT HERE I AM TOO EARLY
    }
  protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        base.OnModelUpdated(controllerContext, bindingContext);
        // IF I DO IT HERE I AM TOO LATE. VALIDATION ALREADY TOOK PLACE
    }
}

最佳答案

也许 RequiredÌf 属性就是您所需要的。 StackOverflow 上有几个关于此的问题。其中之一可以在这里找到:RequiredIf Conditional Validation Attribute .

Darin 还指向一个 blogpost on MSDN包含 RequiredIf 属性的实现。

有了这个属性,你的 View 模型会变成这样:

public class ResponseViewModel {

    public QuestionViewModel Question { get; set; }

    [RequiredIf("Question.IsRequired", true, "This question is required.")]
    public string Answer { get; set; }
}

我不确定我提供的实现是否支持复杂类型的属性(例如 Question.IsRequired),但通过一些修改它应该是可能的。

关于c# - 根据用户未输入的数据验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711836/

相关文章:

c# - 如何将命令绑定(bind)到祖先数据上下文? WPF::MVVM

c# - 如何强制 Visual Studio 在 https 中运行网站

javascript - 下载 MVC FileResult 在 IE 或 Edge 浏览器中不起作用

entity-framework - 如何使用 AutoMapper 将 DTO 映射到 Entity Framework 代理类?

c# - GridView 的内联编辑

c# - 参数为 sbyte 类型的 GetBytes

c# - 序列化时如何按声明顺序获取类属性

javascript - 用表格提交剑道网格

Automapper 表达式必须解析为顶级成员

c# - 将扁平字符串映射到列表