EaBIM一直以来积极响应国家“十二五”推进建筑业信息化的号召,对建筑领域的信息技术开展深入技术交流和探讨!致力于打造“BIM-建筑师-生态技术”三位一体综合资源交流共享平台,希望为BIM与可持续设计理念及技术的普及做出微小的贡献!!!

萧闫子 发表于 2014-1-10 10:26:11

[架构模式] ASP.NET MVC 入门介绍 (下)

接上文,我们来完善验证功能。在System.ComponentModel.DataAnnotations命名空间中,已经有了一些基本的属性类来实现验证功能,只要把这些属性加到Model的字段上就可以了。具体的属性类可以查MSDN, 下面给出一个例子:
public class Movie
{
   
    public int ID { get; set; }
   
    public string Title { get; set; }
   
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
   
    public decimal Price { get; set; }   
    public string Rating { get; set; }
}
  再运行下程序,就可以看到效果:

  当然,默认的验证往往并不足够,可以尝试下将日期改为201-01-1,点击Create,就会引发异常。我们可以增加自定义的验证属性来满足验证要求。下面我们来实现一个DateAttribute属性来实现日期格式和日期范围的检查。新建一个动态链接库Biz.Web,添加System.ComponentModel.DataAnnotations引用,新建一个类如下:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;

namespace Biz.Web
{
   
    public class DateAttribute:ValidationAttribute
    {
      public DateAttribute()
      {
            //set default max and min time according to sqlserver datetime type
            MinDate = new DateTime(1753, 1, 1).ToString();
            MaxDate = new DateTime(9999, 12, 31).ToString();
      }

      public string MinDate
      {
            get;
            set;
      }

      public string MaxDate
      {
            get;
            set;
      }

      private DateTime minDate, maxDate;
      //indicate if the format of the input is really a datetime
      private bool isFormatError=true;

      public override bool IsValid(object value)
      {
            //ignore it if no value
            if (value == null || string.IsNullOrEmpty(value.ToString()))
                return true;
            //begin check
            string s = value.ToString();
            minDate = DateTime.Parse(MinDate);
            maxDate = DateTime.Parse(MaxDate);
            bool result = true;
            try
            {
                DateTime date = DateTime.Parse(s);
                isFormatError = false;
                if (date > maxDate || date < minDate)
                  result = false;
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
      }

      public override string FormatErrorMessage(string name)
      {
            if (isFormatError)
                return "请输入合法的日期";
            return base.FormatErrorMessage(name);
      }
    }
}
  主要实现IsValid方法,如有需要也可以实现FormatErrorMessage方法。要注意属性的参数只能是有限的几种类型,参考这里。写好以后,把HelloWorld项目添加Biz.Web引用,然后就可以使用了,例如:

public DateTime ReleaseDate { get; set; }
  看下效果:
  当然,这种方式有许多限制,主要是属性参数的限制,只能是基本类型,而且只能是常量。更复杂的验证规则的添加请看这里:
  Implement Remote Validation in ASP.NET MVC.
  下面为lndex页面加上一些筛选功能。通过给Index传递参数来实现筛选,在页面添加一个selectbox来筛选Genre字段,把MovieController的方法改成:
public ViewResult Index(string movieGenre)
{
      var genre = (from s in db.Movies
                   orderby s.Genre
                   select s.Genre).Distinct();
      ViewBag.MovieGenre = new SelectList(genre);//给前台准备下拉列表的数据。
      if (!string.IsNullOrEmpty(movieGenre))
      {
          //筛选
          var movies = from s in db.Movies where s.Genre == movieGenre select s;
          return View(movies);
      }
      return View(db.Movies.ToList());
}
  在View页面,添加一个Form,里面放上一个选择框和一个按钮,代码如下:
@using (Html.BeginForm("Index", "Movie", FormMethod.Get))
{
    <p>Genre: @Html.DropDownList("MovieGenre","全部")<input type="submit" value="筛选" /></p>
页: [1]
查看完整版本: [架构模式] ASP.NET MVC 入门介绍 (下)