We are using the JQuery UI datepicker on an MVC project to populate a hidden form field that forms part of our model. The problem we have is when a Modelstate error occurs and the user is returned back to the orginal form they submitted (with the values they selected pre-populated) the JQuery UI datepicker reverts to the current date. We need this to display the date that the user selected. How would we go about doing this?
HTML
<div class="col-md-2">
#Html.LabelFor(model => model.Departure_Date, new { #class = "control-label required" })
</div>
<div class="col-md-3">
<div id="datepicker" class="dateDeparture"></div>
#Html.HiddenFor(model => model.Departure_Date, new { id = "departureDate"})
</div>
Javascript
$(".dateDeparture").datepicker({
altField: "#departureDate",
defaultDate: setDate,
dateFormat: "mm/dd/yyyy"
});
function setDate(){
var date = $('#departureDate').value;
if(date == ""){
date = new Date();
}
return date;
}
As you can see above we try and get teh value of the hidden field and then use that to set the date on the datepicker but this does not work and we get the following error:
TypeError: i.getTime is not a function
http://localhost:49438/scripts/jquery-ui.min.js Line 8
Any help with this issue would be greatly appreciated.
defaultDate expects a string value, you're passing it a function.
You should try executing the function like:
$(".dateDeparture").datepicker({
altField: "#departureDate",
defaultDate: setDate(),
dateFormat: "mm/dd/yyyy"
});
function setDate(){
var date = $('#departureDate').value;
if(date == ""){
date = new Date();
}
return date;
}
Related
I have a very different kind of problem.
I have deployed my mvc application to live server.
It has date time format like this '01/07/2019'.
I have a textbox which is populated from jquery datetimepicker. It populates like this 27/Jul/2019 but in sql table it stores like 2019-07-17 00:00:00.000
and after binding the data from database to textboxfor, it appears like this 27-07-2019.
And upon saving it throws error for all the dates that are greater than 12 as a day e.g. 13/07/2019 but for 13/Jul/2019 it works good.
how to tackle this?
#Html.EditorFor(model => model.InspectionReport.InspectionDate, new { htmlAttributes = new { #class = "form-control input-sm pull-right text-box single-line" } })
jquery:
$("#InspectionReport_InspectionDate").datepicker({ dateFormat: 'dd/M/yy' });
class:
[Required]
[Display(Name = "Inspection Date")]
[DisplayFormat(DataFormatString = "{0: dd-MMM-yyyy}")]
public DateTime InspectionDate { get; set; }
In a date field of data type DateTime(2), a date value is stored as a value with no format.
Thus, to display the value, apply the format you wish, or a default format will be applied.
Try this,
#Html.TextBoxFor(model => model.InspectionReport.InspectionDate, "{0:dd-MMM-yyyy}", htmlAttributes: new { #type="date" })
<div class="input-group" style="margin-bottom:30px;">
<span class="input-group-addon">
Brand
</span>
#Html.DropDownListFor(x => x.BrandMod.Id, c,"- Select Brand - ", new { #class = "form-control" ,id="brandid" })
</div>
"This is My Code for Drop Down and I want to select the selected item. I am trying this"
$("#brandid").change(function (rupp) {
var a = $(this).select("option:selected").val();
});
"I am Unable to Load the Selected item."
This doesn't do what you're thinking:
$(this).select("option:selected").val()
In fact, it's probably either silently failing entirely or producing an error. But no matter. What you're trying to do is get the value from this (which is a <select> in your case). That can be done simply with:
$(this).val()
You don't need Specification for getting value in jquery. You have already change event for this
$("#brandid").change(function (rupp) {
var a = $(this).val();
});
or
var a = $("#brandid").val();
I have value of text box with some date time format (the default that DatePicker supplies - for example - 01/23/2014).
<input type="text" name="OrderDate" value="" id="OrderDate" class="datepicker field field119 datepicker-init" />
I have correlative Property in the model class with the same name and ID as the element in the view.
public DateTime OrderDate { get; set; }
at this point everything is matched and once submit I get the right value in my controller.
Now - I'd like to change the default DatePicker format -
for example:
$(".datepicker").datepicker({
minDate: 0,
dateFormat: 'dd/mm/yy'
});
and I fail to "explain" the model proprty how to serlizae the text box value - instead I get the default DateTime and not my time.
the question : how to change the text box date format that the DateTime property will know how to serialize that?
Ok, here is how you get this working.
Firstly jQuery UI formats the date you need using dd/mm/y, so you need to change your javascript to this:
$(".datepicker").datepicker({
minDate: 0,
dateFormat: 'dd/mm/y'
});
See jsFiddle here:
http://jsfiddle.net/hutchonoid/Fa8Xx/1376/
Then you need to format the model date in the view, you can do this like so:
#Html.TextBoxFor(m => m.OrderDate, String.Format("{0:dd/M/yy}", Model.OrderDate),
new { #class = "datepicker field field119 datepicker-init" })
This works nicely with model binding to when posting the date back to the server.
I have a WebGrid that shows value from my table and an edit button. when a user clicks this button a pop up form or dialog form comes out and its populated with values from the same table I mentioned earlier.
I have managed to format date values and now interested in formatting the boolean value (true/false ) from my table to be displayed in a checkbox. At the moment its displayed as a textbox with value true or false.
Below is part of my code:
$('#dialog-form2-edit').dialog(
{
//dialog form code .. this is fine
$.getJSON('/Methods/GetCertificate/' + $(this).attr('id'), function (data)
{ var certificate = data;
$('#edit-paid').val(certificate.Paid);
$('#edit-mark').val(certificate.Mark);
var date = new Date(parseInt(certificate.MarkDate.substr(6)));
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
$('#edit-markdate').val(year + '-' + month + '-' + day);
$('#edit-markdate').datepicker({ dateFormat: 'yy-mm-dd' });
Below is part of my html
<div id="dialog-form2-edit" title="Edit Certificate">
<form id="edit-certificate-form" action="#Href("~/Methods/UpdateCertificate")">
<div class="row">
<span class="label"><label for="markdate">Mark Date :</label></span>
<input type="text" name="markdate" id="edit-markdate" size="20"/>
</div>
<div class="row">
<span class="label"><label for="mark">Mark :</label></span>
<input type=text" name="mark" id="edit-mark" size="15"/>
</div>
The value Mark and Paid are boolean. Now I intend to have the type changed to text and need help to format the boolean value to checkbox.
If you have a server-side bool value, you can use conditional attributes in Web Pages 2 to manage checkboxes. You provide the bool to the checked attribute of the checkbox using Razor:
#{ var myBool = true; }
<input type="checkbox" name="mark" id="mark" checked="#myBool" />
If the bool is true, checked="checked" is rendered. If it is false, the checked attribute is not rendered at all.
Use this code to display your boolean value in checkbox.
$.getJSON('/Methods/GetCertificate/' + $(this).attr('id'), function (data)
{
var certificate = data;
if(certificate.Pass == true){
$('#edit-pass').attr('checked', 'checked')}
else {$('#edit-pass').removeAttr('checked', 'checked')};
// your other json data
})
The removeAttr is necessary since I am using jquery-1.4.2.min.js. Tested and its working
So I have this form where the user can enter in a start time and end time (for a booking). The values in the database are DateTimes, but the Date part is completely ignored. Currently, when I enter in eg. "5:00 pm" (through a jQuery time picker), it says this is not a valid date. If I type "30/1/2013 5:00 pm" it accepts this as valid... How do I change this behaviour to only validate as a time? (or if that's not ideal, how can I completely turn validation off for that field - I'll manually handle validation in the controller)
I saw this: http://connect.microsoft.com/VisualStudio/feedback/details/705643/a-data-val-date-attribute-is-generated-for-time-fields-in-asp-net-mvc-4# but Microsoft claims it has been fixed; not sure if this is the same problem. I don't want to change the database definition to TimeSpan because I believe it will muck up the existing data (it will won't it?).
Controller:
[HttpPost]
public ActionResult Create(BookingDetailsDate bookingdetailsdates) //, FormCollection collection)
{
if (ModelState.IsValid)
{
try
{
//bookingdetailsdates.StartTime = DateTime.Parse(collection["StartTime"]); // TODO: do this better
//bookingdetailsdates.EndTime = DateTime.Parse(collection["EndTime"]);
bookingdetailsdatesRepository.Add(bookingdetailsdates);
bookingdetailsdatesRepository.Save();
return RedirectToAction("Index", new { id = bookingdetailsdates.BookingDetailsID });
}
catch { }
}
return View(bookingdetailsdates);
}
View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend></legend>
...
#Html.EditorFor(model => model.StartTime)
#Html.EditorFor(model => model.EndTime)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
Editor Template:
<div class="editor-label">
#Html.LabelFor(m => m)
</div>
<div class="editor-field">
#if (Model.HasValue==true)
{
#Html.TextBox("", Model.Value.ToShortTimeString(), new { #class = "TimePicker" })
}
else
{
#Html.TextBoxFor(m => m, new { #class = "TimePicker" })
}
#Html.ValidationMessageFor(m => m)
</div>
I think "DateTime" this data type is not a good choice, if you just want to save time that users save and then compare them in somewhere I suggest to use "nchar" type. Why? Let me explain, datetime is a very complicated type, it has many kinds of forms. Like "2013-1-29 5:00 pm", "2013/1/29 5:00pm". If your purpose is to compare and check if out of date, you can use this way. "201301291700", it's a fixed length which is 12. The benefit of this is 1. you can easy to save it anywhere by type string. 2. you can compare easily by convert to int type or maybe long type.(number is much easier to compare, isn't it?)
Answer is based on my experience, hope it helps you!
So the trouble was in jQuery's validation, even though the metadata for my fields specified it would be a time only (and that wasn't even strictly necessary), jQuery's validate requires the box to contain a full datetime string...
Commenting out these lines fixes the problem:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>