本节主要介绍ASP.Net MVC DropDownList绑定,以及自定义验证。首先看自定义验证,Model代码如下(需要引入System.ComponentModel.DataAnnotations)
using System;
using System.Collections;
using System.ComponentModel.DataAnnotations;

public class SS_CODE
{    
         private string _C_CNAME;
        [Required(ErrorMessage = "不能为空")]
        [StringLength(20, ErrorMessage = ( "不能超过20"))]
         public     string C_CNAME
        {
              get {     return _C_CNAME; }
              set {    _C_CNAME = value; }
        }
}
我们加入两个验证,一个是非空,一个是验证字符串长度。MVC下有下面几种验证。Required:不能为空,StringLength:字符串的长度,Range:数字的可输入范围,RegularExpression:正则表达式匹配,基本和传统的WebForms提供的验证一样。我们看看页面代码
 
< %@ Page Title ="" Language="C#" MasterPageFile ="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage>" %>
< asp:Content ID ="Content1" ContentPlaceHolderID ="TitleContent" runat ="server" >
        Create
asp:Content>
< asp:Content ID ="Content2" ContentPlaceHolderID ="MainContent" runat ="server" >
         < h2 >
                Create h2>
        <% using (Html.BeginForm())
                {%>
         < %: Html.TextBoxFor(model = > model.C_CNAME)%>
         < %: Html.ValidationMessageFor(model = > model.C_CNAME)%>
         < p >
                 < input type ="submit" value ="Create" />
         p>
         < %} % >
asp:Content>
< asp:Content ID ="Content3" ContentPlaceHolderID ="HeadContent" runat ="server" >
asp:Content>
运行一下,效果如图
asp.net MVC2 初探十三_第1张图片
asp.net MVC2 初探十三_第2张图片
接着我们看DropDownList的绑定。先看看控制器代码
public ActionResult Index()
                {
                         try
                        {
                                 object obj = base.GetClass( "CodeDao");
                                List items = ((SS_CodeDao)obj).Select( " from SS_CODE", 5);
                                IEnumerable ie = items.AsEnumerable();
                                SelectList list = new SelectList(ie, "C_DATA", "C_ENAME");
                                ViewData.Add( "items", list);
                                 return View( "~/Views/System/Code/Index.aspx");
                        }
                         catch (Exception e)
                        {
                                ILog lg = log4net.LogManager.GetLogger( "WebLogger");
                                {
                                         if (lg.IsErrorEnabled)
                                        {
                                                lg.Error( this.GetType().ToString() + e.Message);
                                        }
                                }
                                 return View();
                        }
                }
再看看视图

                <%: Html.DropDownList( "ddlCName", ViewData[ "items"] as SelectList, "----选择----")%>
        
 
asp.net MVC2 初探十三_第3张图片
就这么简单,以后我们会讲到下拉列表三级联动。若要实现客户端验证,则需要引入 MicrosoftAjax.js和MicrosoftMvcValidation.js。并在using(Html.BeginForm())前加上Html.EnableClientValidation()即可