c# – ASP.NET MVC中的模型警告
发布时间:2020-12-15 08:33:03 所属栏目:百科 来源:网络整理
导读:我目前正在使用asp.net mvc中的ModelStateDictionary来保存验证错误并将其传递给用户.能够检查整个模型是否对ModelState.IsValid有效是特别的.但是,我正在处理的当前应用程序需要能够报告警告.这些并不重要,因此表单内容仍然可以保存,但应该向用户显示,以便
我目前正在使用asp.net mvc中的ModelStateDictionary来保存验证错误并将其传递给用户.能够检查整个模型是否对ModelState.IsValid有效是特别的.但是,我正在处理的当前应用程序需要能够报告警告.这些并不重要,因此表单内容仍然可以保存,但应该向用户显示,以便可以选择采取措施.
我一直在查看框架,看看是否有任何明显的地方可以扩展它以允许我这样做.我在想另一个带有警告的字典和模型错误的子类称为模型警告.我不确定如何让框架在视图等中使用我的新容器类,但我仍然希望所有现有的错误内容都能正常工作. 如果有人尝试过任何相似或有任何想法,我会很感激他们的意见. 更新: 我已经扩展了ViewDataDictionary以添加一些警告 public class AetherViewDataDictionary : ViewDataDictionary { public AetherViewDataDictionary() { ModelStateWarning = new ModelStateDictionary(); } public AetherViewDataDictionary(object model) : base(model) { ModelStateWarning = new ModelStateDictionary(); } public AetherViewDataDictionary(ViewDataDictionary viewDataDictionary) : base(viewDataDictionary) { ModelStateWarning = new ModelStateDictionary(); } public ModelStateDictionary ModelStateWarning { get; private set; } } 我现在遇到的问题是,当我到达我的视图代码时,这只是用于调试我失去了它的新类型这一事实,所以当我尝试将其强制转换并获取对我的新字典的访问权限时我没有快乐. public partial class Index : ViewPage<PageViewData> { protected override void SetViewData(ViewDataDictionary viewData) { base.SetViewData(viewData); } } 它在这里设置正确,但当我检查它消失的类型. 编辑: 解决方法
所以我之前的路线结果是一个坏主意,在框架中没有足够的访问来获得你需要的位.至少不是没有重新发明轮子几次.
我决定沿着扩展ModelState类的路线向其添加警告集合: public class AetherModelState : ModelState { public AetherModelState() { } public AetherModelState(ModelState state) { this.AttemptedValue = state.AttemptedValue; foreach (var error in state.Errors) this.Errors.Add(error); } private ModelErrorCollection _warnings = new ModelErrorCollection(); public ModelErrorCollection Warnings { get { return this._warnings; } } } 为了能够以与错误相同的方式轻松添加警告,我为ModelStateDictionary创建了一些扩展方法: public static class ModelStateDictionaryExtensions { public static void AddModelWarning(this ModelStateDictionary msd,string key,Exception exception) { GetModelStateForKey(key,msd).Warnings.Add(exception); } public static void AddModelWarning(this ModelStateDictionary msd,string errorMessage) { GetModelStateForKey(key,msd).Warnings.Add(errorMessage); } private static AetherModelState GetModelStateForKey(string key,ModelStateDictionary msd) { ModelState state; if (string.IsNullOrEmpty(key)) throw new ArgumentException("key"); if (!msd.TryGetValue(key,out state)) { msd[key] = state = new AetherModelState(); } if (!(state is AetherModelState)) { msd.Remove(key); msd[key] = state = new AetherModelState(state); } return state as AetherModelState; } public static bool HasWarnings(this ModelStateDictionary msd) { return msd.Values.Any<ModelState>(delegate(ModelState modelState) { var aState = modelState as AetherModelState; if (aState == null) return true; return (aState.Warnings.Count == 0); }); } } GetModelStateForKey代码很复杂但你应该能够看到我的目标.接下来要做的是编写一些扩展方法,允许我显示警告和错误 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |