我有这个 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/