MVC4 表单编辑及显示日期格式

两个方案,分别分四个模块来解释
  1. Controller增加页面控制方法
  2. Model增加字段
  3. View实际页面
  4. 实际效果


方案一:
1,各个模块这个是一样的
        public ActionResult Edit(int id = 0)
        {
            StaffInfo staffInfo = db.StaffInfo.Find(id);
            if (staffInfo == null)
            {
                return HttpNotFound();
            }
            return View(staffInfo);
        }
2,Model中字段属性增加DateType(这里格式不能改)
        [DisplayName("生日")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        [DataType(DataType.Date)]
        public Nullable<DateTime> BirthDate { get; set; }
3,View中使用Editor
        <div class="editor-label">
            @Html.LabelFor(model => model.BirthDate)
        </div>
        <div class="editor-field">
          :  @Html.EditorFor(model => model.BirthDate)
             @Html.ValidationMessageFor(model => model.BirthDate)
        </div>
4, 显示及编辑效果

方案二:
2,模型不做设置
        [DisplayName("生日")]
       public Nullable<DateTime>BirthDate { get;set; }
3.1,View中使用TextBoxFor
       <divclass="editor-label">
           @Html.LabelFor(model=> model.BirthDate)
       </div>
       <divclass="editor-field">
          : @Html.TextBoxFor(model=> model.BirthDate,"{0:yyyy年MM月dd日}",new { @class = "datetype",type = "text" })
            @Html.ValidationMessageFor(model=> model.BirthDate)
       </div>
3.2,新建脚本文件
$(function() {
   $.validator.addMethod('date',
   function (value,element){
       if (this.optional(element)){
           return true;
       }
       var valid = true;
       try {
           $.datepicker.parseDate('yy年mm月dd日',value);
       }
       catch (err){
           valid = false;
       }
       return valid;
   });
   $(".datetype").datepicker({dateFormat:'yy年mm月dd日' });
});
3.3 增加Jquery库函数调用
@section Scripts {
   @Styles.Render("~/Content/themes/base/css")
   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/jqueryui")
   @Scripts.Render("~/bundles/jqueryval")
}
3.4增加脚本引用(在库函数之后)
<script src="~/Scripts/datepicker.js"></script>
4,实际效果


猜你喜欢

转载自blog.csdn.net/suoxd123/article/details/78367445