2012-07-05 27 views
0

感谢您的任何想法。asp.net mvc3动态验证和实体框架

虽然我正在通过一些自定义validationAttributes的方式工作,但我遇到了一个应该很简单的问题,但让我难住了。

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

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

谢谢你一如既往。

回答

0

这是我想出了,但渴望知道是否有更好的解决方案:

命名约定允许automapper扁平化模式(每个StudyCentre具有与RecordSystem一个多对1间的关系(有些系统共享患者索引系统)

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

作为视图模型内的嵌套类用于indidual TrialParticipant

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是为标签) 函数的正则表达式仅仅是:

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; 
    } 
} 

该控制器建立视图模型像这样:

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>