.net 4.5 webform 提取ModelState错误信息

时间:2021-01-05 20:36:21

.net4.5以后,webform也可以使用模型绑定和模型验证。

user实体:

public class User
{
[Required]
[Display(Name = "用户ID")]
public int Id { get; set; }
[Required]
[StringLength()]
[Display(Name = "用户名")]
public string UserName { get; set; }
[Required]
[StringLength()]
[Display(Name = "用户密码")]
public string PassWord { get; set; }
}

模型自动绑定和验证:

var user = new Model.User();
var formValueProvider = new FormValueProvider(ModelBindingExecutionContext);
TryUpdateModel(user, formValueProvider);
//模型验证
if (ModelState.IsValid)
{
Response.Write(user.UserName);
}

前台接收验证信息

<asp:ValidationSummary runat="server" EnableViewState="True"/>

如果不用服务器控件,接受错误信息可以这么做

建立名为ModelStateErrorHandler的ModelState扩展方法

public static class ModelStateErrorHandler
{
/// <summary>
/// ModelState扩展,取得Dictionary类型的错误信息
/// </summary>
/// <param name="errDictionary"></param>
/// <returns>
/// Key: 字段名
/// Value: 字段错误信息
/// </returns>
public static Dictionary<string, string> GetModelErrors(this ModelStateDictionary errDictionary)
{
var errors = new Dictionary<string, string>();
foreach (var pair in errDictionary.Where(k => k.Value.Errors.Count > ))
{
var er = string.Join(",", pair.Value.Errors.Select(e => e.ErrorMessage));
errors.Add(pair.Key, er);
}
return errors;
}
/// <summary>
/// ModelState扩展,取得string类型的错误信息
/// </summary>
/// <param name="errDictionary"></param>
/// <returns>
/// 以|分割错误信息
/// </returns>
public static string GetModelErrorsString(this ModelStateDictionary errDictionary)
{
var errorsBuilder = new StringBuilder();
var errors = errDictionary.GetModelErrors();
foreach (var key in errors)
{
errorsBuilder.AppendFormat("{0}:{1}|", key.Key, key.Value);
}
return errorsBuilder.ToString();
}
}

调用:

var errorsDictionary = ModelState.GetModelErrors();
string jsonstr = new JavaScriptSerializer().Serialize(errorsDictionary);
var errorsString = ModelState.GetModelErrorsString();

在模板解析json或者字符串即可。

.net 4.5 以后很多mvc的特性webform也可以使用了。。爽啊