ASP.NE“.NET研究”T MVC 入门介绍 (下)
2011-10-19 19:38 狼人:-) 阅读(179) 评论(0) 编辑 收藏 举报相关文章:ASP.NET MVC 入门介绍 (上)
接上文,我们来完善验证功能。在System.ComponentModel.DataAnnotations命名空间中,已经有了一些基本的属性类来实现验证功能,只要把这些属性加到Model的字段上就可以了。具体的属性类可以查MSDN, 下面给出一个例子:
public class Movie
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(10,MinimumLength=2,ErrorMessage="必须是2~10个字符长"),Required,Display(Name="名称")]
public string Title { get; set; }
[Display(Name="发布日期")]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Range(1,100,ErrorMessage="必须是1~100")]
public decimal Price { get; set; }
public string Rating { get; set; }
}
再运行下程序,就可以看到效果:
上海闵行企业网站制作 src="https://images.cnblogs.com/cnblogs_com/yinzixin/201105/201105061718303626.png" border="0" alt="image" width="387" height="494" />
当然,默认的验证往往并不足够,可以尝试下将日期改为201-01-1,点击Create,就会引发异常。我们可以增加自定义的验证属性来满足验证要求。下面我们来实现一个DateAttribute属性来实现日期格式和日期范围的检查。新建一个动态链接库Biz.Web,添加System.ComponentModel.DataAnnotations引用,新建一个类如下:
using System;
using上海企业网站制作 style="color: #000000;"> System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
namespace Biz.Web
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class DateAttribute:ValidationAt上海徐汇企业网站制作tribute
{
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引用,然后就可以使用了,例如:
[Display(Name="发布日期"),Date(MaxDate="2012-01-01",ErrorMessage="2012地球灭亡啦")]
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 上海徐汇企业网站设计与制作yle="color: #000000;">== 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>
}
效果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南