asp.net mvc3动态验证和实体框架

时间:2012-07-05 06:22:41

标签: asp.net-mvc-3 validation

感谢您的任何想法。

当我正在通过一些自定义validationAttributes时,我遇到了一个问题,应该很简单,但让我感到难过。

授权用户将拥有一个UserProfile,其中包含他们所在站点的密钥。该站点是数据库中的记录集。此站点记录集中的1个字段是一个正则表达式,表示在完全独立的表中字段的有效格式。输入此另一个表的数据对所有注册用户都是通用的,但特定字段与其所在机构使用的ID格式有关。

有没有一种干净的方法可以动态地将正则表达式验证器添加到属性中?

一如既往地感谢你。

1 个答案:

答案 0 :(得分:0)

这就是我想出来的,但又想知道是否有更好的解决方案:

命名约定是允许automapper压缩模型(每个StudyCentre与RecordSystem有一对多的关系(某些系统共享患者索引系统)

Mapper.CreateMap<StudyCentre, ParticipantRegistration.StudyCentreViewData>();

作为一个独立的TrialParticipant

的ViewModel中的嵌套类
public StudyCentreViewData ViewData { get; set; }
public class StudyCentreViewData
{
    public string Abbreviation { get; set; }
    public string RecordSystemName { get; set; }
    public string RecordSystemHospitalNoRegEx { get; set; }
    public string RecordSystemNotationDescription { get; set; }
    public IDictionary<string, object> HospitalNoRegEx()
    {
         return DynamicClientValidation.RegEx(errorMessage:String.Format("{0} must consist of {1}",
                                                                       RecordSystemName,
                                                                       RecordSystemNotationDescription),
                                              regExPattern: RecordSystemHospitalNoRegEx);
    }
}

其他属性(例如StudyCentre.Abbreviation用于标签) RegEx函数只是:

public static class DynamicClientValidation
{
    public static IDictionary<string, object> RegEx(string errorMessage, string regExPattern)
    {
        var returnVal = new Dictionary<string, object>(3);
        returnVal.Add("data-val-regex", errorMessage);
        returnVal.Add("data-val-regex-pattern", regExPattern);
        returnVal.Add("data-val", "true");
        return returnVal;
    }
}

Controller设置viewmodel,如下所示:

model.ViewData = Mapper.Map<StudyCentre, ParticipantRegistration.StudyCentreViewData>(_studyCentre.GetCentreByUser(_currentUserName));

并在视图中(LabelDetailsfor是一个自定义助手):

<div class="editor-label">
    @Html.LabelDetailsFor(model => model.HospitalID,Model.ViewData.Abbreviation + " ID", Model.ViewData.RecordSystemName) 
</div>
<div class="editor-field">
    @Html.TextBoxFor(model => model.HospitalID, Model.ViewData.HospitalNoRegEx())
    @Html.ValidationMessageFor(model => model.HospitalID)
 </div>