using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalkingTec.Mvvm.Core; namespace WalkingTec.Mvvm.Mvc { /// /// 模拟MVC中的ModelState类 /// public class ModelStateServiceProvider : IModelStateService { private ModelStateDictionary _states; public ModelStateServiceProvider(ModelStateDictionary s) { this._states = s; } public List this[string name] { get { return _states?[name].Errors.Select(x => new MsdError { ErrorMessage = x.ErrorMessage, Exception = x.Exception }).ToList(); } } /// /// 添加错误信息 /// /// 错误的字段名 /// 错误信息 public void AddModelError(string key, string errorMessage) { if (string.IsNullOrEmpty(key)) { key = Guid.NewGuid().ToString(); } _states.AddModelError(key, errorMessage); } public void RemoveModelError(string key) { _states.Remove(key); } public void Clear() { _states.Clear(); } public int Count => _states.Count; public IEnumerable Keys => _states.Keys; bool IModelStateService.IsValid => _states.IsValid; public string GetFirstError() { string rv = ""; foreach (var key in Keys) { if(this[key].Count > 0){ rv = this[key].First().ErrorMessage; } } return rv; } } }