Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

asp.net mvc - jquery ui datepicker and mvc view model type datetime

I am using jquery datepicker on my view model

Here is my view:

@Html.TextBoxFor(o => o.JobStartDate, new { id = "dt1", @class = "input-block-level" })
@Html.ValidationMessage("JobStartDate")

and my script:

$("#dt1").datepicker({ dateFormat: "dd/mm/yy" });

Everything works fine if my date is <= 12, if my date is over 12, it will show me an validation error message saying "The field Start Date must be a date." (I am using jquery validation)

For example: date 16/12/2014 will give me the error while 12/12/2014 won't

Here is my view model:

[Required]
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
public DateTime JobStartDate { get; set; }

I am suspecting that my view model is anticipating a date in the format mm/dd/yyyy while on my datepicker i specified dd/mm/yy, is there a way to tell my viewmodel that I am expecting dd/mm/yy format so that it doesn't throw an error message if date is >= 12.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can look at using the jquery globalize or add the following to your script (assuming of course that the server culture date format is 'dd/MM/yyy')

$.validator.addMethod('date', function (value, element) {
  if (this.optional(element)) {
    return true;
  }
  var valid = true;
  try {
    $.datepicker.parseDate('dd/mm/yy', value);
  }
  catch (err) {
    valid = false;
  }
  return valid;
});
$('#dt1').datepicker({ dateFormat: 'dd/mm/yy' });

and please use @Html.ValidationMessageFor(m => m.JobStartDate)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...