ASP.NET MVC数据验证(上)

关于ASP.NET MVC的验证,用起来很特别,因为MS的封装,使人理解起来很费解。也可能很多人都在Scott Guthrie等人写的一本《ASP.NET MVC 1.0》书中,见过NerdDinner项目中对Dinner对象修改和添加的时的数据验证。但有许多封装的地方,不知道是怎样的工作原理,今天研究了,拿出来给大家分享一下。
数据库还是上一篇blog中的库与表,同样的方法来创建news表的实体类,在自动生成的news这个实体类中,我们发现有一个特殊的分部方法:
partial void OnValidate(System.Data.Linq.ChangeAction action);<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

这个方法没有实现,我们根据C#的语法知道,如果分部类中的分部方法,没有实现的话,调用和定议的地方都不会起什么作用。现在,我们要去完善这个方法,让它“用”起来。
首先,人产在Models中创建news类的另一部分,代码如下:
    public partial  class news

    {

        partial void OnValidate(System.Data.Linq.ChangeAction action)

        {

            if (!IsValid)

            {

                throw new ApplicationException(" 验证内容项出错!" );

            }

        }

        public bool IsValid

        {

            get { return (GetRuleViolations().Count() == 0); }

        }

        public IEnumerable<RuleViolation> GetRuleViolations()

        {

            if (String.IsNullOrEmpty(this.title .Trim () ))

                yield return new RuleViolation(" 题目步能为空!" , " 题目" );

            if (String.IsNullOrEmpty(this.contents .Trim ()))

                yield return new RuleViolation(" 内容不能为空!" , " 内容" );         

            yield break;

        }

    }

/// <summary>

    /// 规则信息类

    /// </summary>

    public class RuleViolation

    {

        public string ErrorMessage { get; private set; }

        public string PropertyName { get; private set; }

 

        public RuleViolation(string errorMessage)

        {

            ErrorMessage = errorMessage;

        }

 

        public RuleViolation(string errorMessage, string propertyName)

        {

            ErrorMessage = errorMessage;

            PropertyName = propertyName;

        }

    }

在这里给出这么多代码,其实是提前有设计的,因为从业务角度考虑,还不应该写这部分代码。RuleViolation类很简单,就是一个包括了两个属性的类(这个类的结构设计是根据后面的ModelState.AddModelError主法来设计的)。
news分部类中,有一个IsValid的属性,这个属性是bool类型的,返回值取决于GetRuleViolations这个方法,这个方法返回值是一个IEnumerable<RuleViolation>类型的,IEnumerable是通过news的几个属性是否为空来生成跌代的。如果titlecontentsNull””,就返回跌代。其实真正的用户数据的验证就是在这里实现,用户的数据的对与错,就是一个逻辑,只要用户数据不符合规则,就可以 “yield return new RuleViolation("错误标识","错误提示信息!");这里的错误码提示信息是显示到客户端的,所以要处理好友好的提示。
现在验证用户数据,生成错误列表的工作都做完了,但关键是怎么能让用户提交数据时,调用OnValidate。这个问题,先放一下,请记住,上面的代码,只要在用户提交数据时,调用OnValidate,这样就能得到错误集合。
现在,让我们来处理CotrollerView层,在Cotroller层,首先来添加index这个Action,代码如下:
public ActionResult Index()

        {          

            var NewsList = DCDC.news.Select(newss=>newss);

            return View(NewsList );

     }
这个Action返回所有news表中的记录。
对应的View如下:
<% @ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcCompany.Models.news>>" %>

 

< asp : Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

     Index

</ asp : Content >

 

< asp : Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 

    <h2>Index</h2>

 

    <table>

        <tr>

            <th></th>

            <th>

                ID

            </th>

            <th>

                title

            </th>

            <th>

                datetimes

            </th>

            <th>

                contents

            </th>

            <th>

                IsValid

            </th>

        </tr>

 

    <% foreach (var item in Model) { %>

   

        <tr>

            <td>

                <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |

                <%= Html.ActionLink("Details", "Details", new { id=item.ID })%>

            </td>

            <td>

                <%= Html.Encode(item.ID) %>

            </td>

            <td>

                <%= Html.Encode(item.title) %>

            </td>

            <td>

                <%= Html.Encode(String.Format("{0:g}", item.datetimes)) %>

            </td>

            <td>

                <%= Html.Encode(item.contents) %>

            </td>

            <td>

                <%= Html.Encode(item.IsValid) %>

            </td>

        </tr>

   

    <% } %>

 

    </table>

 

    <p>

        <%= Html.ActionLink("Create New", "Create") %>

    </p>

 

</ asp : Content >

 

代码中,需要我们注意是的     <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值