Default Empty value in Kendo DatePicker - kendo-ui

I need the default value of datetime picker to be empty.
#(Html.Kendo().DatePickerFor(model => model.RevisionDate)
.Name("RevisionDate")
)
"RevisionDate" is a datetime property in a asp.net mvc model.
how it's currently being displayed
and i need to display it as below

Your RevisionDate property is by default set to DateTime.MinValue which is 01/01/0001 ( all DateTime properties behave like that). This is why the Kendo UI DatePicker shows it like that. The solution is to make the property a nullable DateTime (DateTime?) whose default value is null.

If you don't want to make the property nullable, you can also do it like this:
#(Html.Kendo().DatePickerFor(m => m.Property).HtmlAttributes(new { value = "" }))

I had the same problem with a ComboBoxFor ComboBoxFor(m => m.LocationId).Value(Model.LocationId == 0 ? string.Empty : Model.LocationId.ToString()).
But I see that this approach doesn't work on the DatePickerFor(It could be a bug).
A workaround could be made in JS if($('#RevisionDate ').val() == "1/1/0001") { $('#RevisionDate ').val("") } but I would recommand Atanas's approach with a nullable field.

Blank out the field from the client side using something like this in your markup/cshtml file :
<script>
// Blank out the 1/1/0001 12:00 AM from the date field
$('#RevisionDate').val("");
</script>

Related

Filter Kendo Grid column with Date picker

I have a Kendo MVC Grid that has a column with a DateTime column. Everything looks good and formats correctly. When i filter, it gives me a date picker and a time picker. When i remove the DateTimeFilter Template below and use template contains, it will give me a Date picker (which i want), but still wants to filter by the date and time.. Is there a way i can have the date and time all as the same field, but only filter with a Date picker.? Example: i use the Date picker to pick 07/24/2017 and it filter everything on that date regardless of time.. Or do they need to be completely different fields, or even concatenated fields in the same column.?
the Column data looks as such: 07/24/2017 18:12:00
columns.Bound(c => c.CreatedDate).Title("Submitted On")
.ClientTemplate("#= kendo.toString(kendo.parseDate(CreatedDate), 'MM/dd/yyyy HH:mm:ss') #")
.Filterable(ftb => ftb.Cell(cell => cell.Template("DateTimeFilter")));
If you're using MVC, in your model, you add DataType.Date above your DatePicker property as below:
[DataType(DataType.Date)]
public DateTime SubmittedOn{ get; set; }
Note: add reference to System.ComponentModel.DataAnnotations if its not included in your header.

Model binding fails with Kendo MultiSelect

In the model I have long? field that I like to use Kendo MultiSelect for it. The main reason for this choice is server-side filtering. It doesn't reflect current Model's value, nor it sends any value to the server. By inspected traffic, I'm sure that it doesn't update the model's value.
#(Html.Kendo().MultiSelectFor(x => x.theField)
.Name("msname")
.MaxSelectedItems(1)
.Placeholder("")
.HighlightFirst(true)
.DataValueField("Id")
.DataTextField("Text")
.AutoBind(true)
.DataSource(ds =>
ds.Read(" ", "API").ServerFiltering(true))
.Value(new long?[] { Model.theField})
)
I can put a hidden field and update its value or multiselect's change, but there should be a better solution.
I should note that this multi select is in an editor template and is used by Kendo Grid in popup editor.
UPDATE
When using nullable types, you need to use ValuePrimitive(true)! So the end code is:
#(Html.Kendo().MultiSelectFor(x => x.theField)
.MaxSelectedItems(1)
.Placeholder("")
.HighlightFirst(true)
.DataValueField("Id")
.DataTextField("Text")
.AutoBind(true)
.DataSource(ds =>
ds.Read(" ", "API").ServerFiltering(true))
.ValuePrimitive(true)
)
The main reason for this choice is server-side filtering
You can find on their demo site that DropDownList and ComboBox also support that feature. But if you insist to use MultiSelect then lets dig some of your code.
Look Name() method will give a name for your input element e.g (input, select). When form serialized it will use our input name as form's field property. If you are using HtmlHelper that ends with "For" e.g (LabelFor, MultiSelectFor) input attribute name will be named by its binded property.
Html.Kendo().MultiSelectFor(x => x.theField)
You will have
<select name="theField"> ....
You don't have to use Name() method anymore, therefore MultiSelect value will be binded as theField property as per form serialized to server.
Now if you look to Request.Form["theField"] when you debug inside your controller, you will see what value being sent. It usually a content of joined string array if multiple items selected, so you need to change theField type to handle array of string or int instead of nullable long type.
EDIT
At last you find the way to solve your problem, this solution credit to Akbari
When using nullable types, you need to use .ValuePrimitive(true)

how to get selected value for Kendo DropDownList

I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:
#model KendoApp.Models.SelectorViewModel
The ViewModel is defined as:
public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
and in My view I have:
#(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?
For anyone who found this wondering how to get the selected value in JavaScript, this is the correct answer:
$("#EncounterTypes").data("kendoDropDownList").value();
From the documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-value
when select a value from a dropdown list, and in the selec event , we can get the selected value as following ,
#(Html.Kendo().DropDownList()
.Name("booksDropDown")
.HtmlAttributes(new { style = "width:37%" })
.DataTextField("BookName")
.DataValueField("BookId")
.Events(x => x.Select("onSelectBookValue"))
.DataSource(datasource => datasource.Read(action => action.Action("ReadBookDropDow", "PlanningBook").Type(HttpVerbs.Get)))
.OptionLabel("Select"))
javascript function like following ,
function onSelectBookValue(e) {
var dataItem = this.dataItem(e.item.index());
var bookId = dataItem.BookId;
//other user code
}
I believe this will help someone
Thanks
Hello I was just going through this problem,kept on searching for 2 hours and came up with a solution of my own.
So here is the line to fetch any data bidden to the kendo drop down.
$("#customers").data("kendoDropDownList").dataSource._data[$("#customers").data("kendoDropDownList").selectedIndex].colour;
Just change the id customers to the id you have given tot he kendo drop down.
Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:
#(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.
BUT should you need to use the hidden field for some reason, put it there, subscribe the the select event of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.
It's your choice :)
If you want to read also out the text of the dropdown, you can get or set the value by using the following kendo function:
$('#EncounterTypes').data("kendoDropDownList").text();
REFERENCE TO THE DOCUMENTATION
Using this .val() as #Vivek Parekh mentions will not work - there is no function .val() in the kendo framework.
If you want you could use jQuery and get the value back: $('#EncounterTypes').val()
Updated DEMO
$("#EncounterTypes").kendoDropDownList().val();
You can get the selected item like following code and then use item.property to get further information
var selectedFooType = $("#fooType").data("kendoDropDownList").dataItem();
selectedFooType.name
//OR
selectedFooType.id

MVC 3 Razor and the display of null dates in forms

I have an MVC 3 website where I display dates in forms using:
<div class="editor-label control-label">
#Html.LabelFor(m => m.rrsfWoman.DateOfBirth)
</div>
<div class="editor-field controls">
#Html.EditorFor(m => m.rrsfWoman.DateOfBirth)
#Html.ValidationMessageFor(m => m.rrsfWoman.DateOfBirth)
</div>
The date of birth is defined in the rrsfWoman class as
public DateTime WomansDateOfBirth { get; set; }
My problem is that as the date of birth field has by default a value of MinDate. Is there a way I can supress the display of the date as 1/01/0001 without making the field nullable.
Thanks
Is there a way I can supress the display of the date as 1/01/0001
without making the field nullable.
The correct way to achieve that is to make the date nullable in your view model. If you don't do that later you will struggle with model binding as well because a non-nullable DateTime field cannot be bound to an empty string and you will have to write custom model binders and stuff to make it work. You will make your life miserable if you don't use view models.
This being said, if you want to go against good practices, you could define a custom editor template for the DateTime type that will perform the check and use an empty value but honestly I don't recommend you doing that:
~/Views/Shared/EditorTemplates/DateTime.cshtml:
#model DateTime
#if (Model == default(DateTime))
{
#Html.TextBox("", "")
}
else
{
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue)
}
You could set the default value of WomansDateOfBirth explicitly like so:
private DateTime _womansDateOfBirth = DateTime.Now;
public DateTime WomansDateOfBirth
{
get { return _womansDateOfBirth; }
set { _womansDateOfBirth = value; }
}
Where DateTime.Now is your MinDate.
If the date field does not allow nulls and you want to force the user to enter a date.
IMO, the best way is to simply clear the input field after the form is built.
So add this little snip-it at the end of your view.
<script type='text/javascript'>
document.getElementById("DateOfBirth").value = "";
</script>

MVC 3 - Change Html.TextBox to Html.TextBoxFor

I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
#Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
#Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.
However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:
Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
Use Html.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
#inherits System.Web.Mvc.WebViewPage<System.DateTime>
with this:
#model System.DateTime?

Resources