学习、分享、快乐
当前位置 >> 68楼学习网学习教育电脑学习编程入门NET教程ASP.NET MVC 入门介绍 (下)

ASP.NET MVC 入门介绍 (下)

[08-23]   来源:http://www.68lou.com  NET教程   阅读:808

ASP.NET MVC 入门介绍 (下),本站还有更多关于NET教程,asp.net教程,net教程的文章。
正文:

我们来完善验证功能。在System.ComponentModel.DataAnnotations命名空间中,已经有了一些基本的属性类来实现验证功能,只要把这些属性加到Model的字段上就可以了。具体的属性类可以查MSDN, 下面给出一个例子:

public class Movie
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { getset; } 
    [StringLength(10,MinimumLength=2,ErrorMessage="必须是2~10个字符长"),Required,Display(Name="名称")]
    public string Title { getset; }
    [Display(Name="发布日期")]
    public DateTime ReleaseDate { getset; }
    public string Genre { getset; }
    [Range(1,100,ErrorMessage="必须是1~100")]
    public decimal Price { getset; }    
    public string Rating { getset; }
}

  再运行下程序,就可以看到效果:

image

  当然,默认的验证往往并不足够,可以尝试下将日期改为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
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class DateAttribute:ValidationAttribute
    {
        public DateAttribute()
        {
            //set default max and min time according to sqlserver datetime type
            MinDate = new DateTime(175311).ToString();
            MaxDate = new DateTime(99991231).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引用,然后就可以使用了,例如:

[Display(Name="发布日期"),Date(MaxDate="2012-01-01",ErrorMessage="2012地球灭亡啦")]
public DateTime ReleaseDate { getset; }

  看下效果:

image  当然,这种方式有许多限制,主要是属性参数的限制,只能是基本类型,而且只能是常量。更复杂的验证规则的添加请看这里:

  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>
}

  效果如下:

image




如果觉得ASP.NET MVC 入门介绍 (下)不错,可以推荐给好友哦。
Tag:NET教程asp.net教程,net教程电脑学习 - 编程入门 - NET教程