这是我想出了,但渴望知道是否有更好的解决方案:
命名约定允许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>