MVC自定义编辑视图,DateTime类型属性显示jQuery ui的datapicker

时间:2024-08-23 10:07:08

实现的效果为:在编辑视图中,对DateTime类型的属性,显示jQuery UI的datepicker。效果如下:

MVC自定义编辑视图,DateTime类型属性显示jQuery ui的datapicker

Student.cs

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime? JoinTime { get; set; }
    }

HomeController:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Student(){Id = 1, JoinTime = DateTime.Now, Name = "Darren"});
        }

}

Views/Shared/EditorTemplates文件夹中创建DateTime.cshtml,视图名称必须和属性类型保持一致。另外,这里时间格式的设置必须和datepicker保持一致。

@model DateTime?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("yyyy-MM-dd") : "", new {@class = "date"})

Home/Index.cshtml视图中:

@model MvcApplication1.Models.Student
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />
 
@using (Html.BeginForm())
{
    @Html.EditorForModel()
}
 
@section scripts
{
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('.date').datepicker({
                dateFormat: 'yy-mm-dd'
            });
        });
    </script>
}
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }