MVC 验证和异常处理 自动验证使用 IDataErrorInfo 接口


除了DataAnnotationsModelValidationFactory,还有DataErrorInfoModelValidatorProvider。DataErrorInfoModelValidatorProvider提供另一种自定义数据合法性验证支持。Asp.net mvc硬编码支持IDataErrorInfo接口。使用方法为model实现IDataErrorInfo。IDataErrorInfo要求实现返回model级别和属性级别违法信息。

示例:

public class Appointment : IDataErrorInfo

{

public string ClientName { get; set; }

public DateTime AppointmentDate { get; set; }

public string this[string columnName]

{

get {

if (columnName == "ClientName") {

if (string.IsNullOrEmpty(ClientName))

return "Please enter a name.";

}

if (columnName == "AppointmentDate")

{

if (AppointmentDate < DateTime.Now.Date)

return "Bookings cannot be placed in the past";

}

return null; // No property-level errors

}

}

public string Error

{

get {

if (ClientName == "Steve"

&& AppointmentDate.DayOfWeek == DayOfWeek.Saturday)

return "Steve can't book on Saturdays.";

return null; // No object-level errors

}

}

}

public ActionResult MakeBooking(Appointment appt, bool acceptsTerms)

{

if (!acceptsTerms)

ModelState.AddModelError("acceptsTerms", "You must accept the terms");

if (ModelState.IsValid) {

// To do: Actually save the appointment to the database or whatever

return View("Completed", appt);

}

else

return View(); // Re-renders the same view so the user can fix the errors

}

优质内容筛选与推荐>>
1、第13章 综合技术
2、编程程序[置顶] 【强烈推荐】程序猿们,九度Online Judge开始举办月赛啦!!会编程才是王道!!!!!
3、Oracle中Decode()函数运用手段
4、自我的成长
5、今天更换了博客地址


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号