バリデーション - 日付(Datepicker)実装例Controller namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Edit()
{
FooEditModel model = new FooEditModel
{
Foo = new Foo
{
Name = "Taro",
Date = new DateTime(2010,12,15)
}
};
return View(model);
}
[HttpPost]
public ActionResult Edit(Foo foo)
{
string message = null;
if (ModelState.IsValid)
{
Debug.WriteLine(foo.Date.ToString());
message = "Saved " + DateTime.Now;
}
FooEditModel model = new FooEditModel
{
Foo = foo,
Message = message
};
return View(model);
}
}
}
コントローラでは特別な事はしない。 Entity public class Foo
{
public string Name { get; set; }
[DataType(DataType.Date)]
[DateRange("2010/12/01","2010/12/16")]
public DateTime Date { get; set; }
}
時間を切り捨てて日付のみを表示する為にDateType(DateType.Date)アノテーションを設定する。 ViewModel public class FooEditModel
{
public string Message { get; set; }
public Foo Foo { get; set; }
}
Views\Home\Edit.cshtml @Model.Message
@using (Html.BeginForm()) {
@Html.TextBoxFor(m => m.Foo.Name)
@Html.EditorFor( m => m.Foo.Date, "Date")
<input id="submit" name="submit" type="submit" value="Save" />
}
EditorForで"Date"を指定して自作テンプレートを呼び出す。 Views\Home\EditorTemplate\Date.cshtml @model DateTime
@Html.TextBox("", Model.ToString("yyyy/MM/dd"), new { @class = "date" })
TextBox(IPUTタグ)にCSSクラスdateを指定する。 @model DateTime
@Html.TextBox("", Model.ToString("yyyy/MM/dd"), new { @class = "date" })
Views\Shared\_Layout.cshtml <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - マイ ASP.NET アプリケーション</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
<link href="~/Content/themes/custom-theme/jquery-ui-1.10.4.custom.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.10.4.js"></script>
<script src="~/Scripts/EditorHookup.js"></script>
</head>
Scripts\EditorHookup.js $(document).ready(function () {
$('.date').datepicker({ dateFormat: "yy-mm-dd" });
});
CSSクラスにdateが指定されている要素に対してjQueryUIのdatepicker()を指定する。 参考
|
|