バリデーション

Controller

 using WebApplication1.Models;
 
 namespace WebApplication1.Controllers
 {
     public class HomeController : Controller
     {
         public ActionResult Index(User model)
         {
             if (ModelState.IsValid) {
                 ViewBag.Mesg = "ModelState.IsValid => OK";
             }
             else {
                 ViewBag.Mesg = "ModelState.IsValid => NO";
             }
 
             ModelState.AddModelError("Foo", "Foo is always Error");
 
             return View(model);
         }
     }
 }

View

 @using WebApplication1.Models;
 @model User
 
 <p>@ViewBag.Mesg</p>
 
 @Html.ValidationSummary(false)
 
 @using(Html.BeginForm("Index", "Home", FormMethod.Post)) {
     @Html.LabelFor(model => model.Id)
     @Html.EditorFor(model => model.Id)
     @Html.ValidationMessageFor(model => model.Id)
     <br />
     @Html.LabelFor(model => model.Name)
     @Html.EditorFor(model => model.Name)
     @Html.ValidationMessageFor(model => model.Name)
     <br />
     @Html.LabelFor(model => model.Age)
     @Html.EditorFor(model => model.Age)
     @Html.ValidationMessageFor(model => model.Age)
     <br />
     @Html.LabelFor(model => model.Sex)
     @Html.DropDownListFor(model => model.Sex, new SelectListItem[] {
         new SelectListItem() {  Value="1", Text="男"},
         new SelectListItem() {  Value="2", Text="女"},
     })
     <br />
     @Html.ValidationMessageFor(model => model.Sex)
     <input type="submit" value="submit" />
 }

Model

 namespace WebApplication4.Models
 {
     public class User
     {
         private int _sex = 2;
 
         [DisplayName("ID")]
         [Required(ErrorMessage = "IDは必須です")]
         public int Id { get; set; }
 
         [DisplayName("名前")]
         [Required]
         public string Name { get; set; }
 
         [DisplayName("性別")]
         [Required]
         [RegularExpression(@"^(1|2)$")]
         public int Sex
         {
             get { return _sex; }
             set { _sex = value; }
         }
 
         [DisplayName("年齢")]
         public int? Age { get; set; }
     }
 }

参考

Model Validation
http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx
@Html.EditorForのデフォルト値
http://weblogs.asp.net/jalpeshpvadgama/archive/2011/08/16/setting-default-value-for-html-editorfor-in-asp-net-mvc.aspx
Htmlヘルパー
http://www.atmarkit.co.jp/fdotnet/aspnetmvc3/aspnetmvc3_06/aspnetmvc3_06_03.html
モデル・バインドとアノテーション検証の実装
http://www.atmarkit.co.jp/fdotnet/aspnetmvc3/aspnetmvc3_04/aspnetmvc3_04_01.html
検証属性の自作とクラス・レベルのモデル検証
http://www.atmarkit.co.jp/fdotnet/aspnetmvc3/aspnetmvc3_05/aspnetmvc3_05_01.html

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS