バリデーション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; }
}
}
System.ComponentModel.DataAnnotations 名前空間http://msdn.microsoft.com/ja-jp/library/system.componentmodel.dataannotations(v=vs.110).aspx 参考
|
|