I have an MVC Kendo Timepicker for that I am using. It works fine except that I can't format the time to Military time. After I add the formatting for Military time, once I select the time the validation doesn't pass and it tells me it must be a date. Is there a way to format the TimePickerFor to allow military time?
#using Kendo.Mvc.UI
#model DateTime?
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Min("05:00")
.Max("00:00")
.Format("{0:HHmm}")
)
Update: This doesn't work with format being changed to .Format("HHmm")
Ok, so thanks to the Kendo people, I found the answer. The script may need some work depending on the situation. My TimePickerFor is in an Editor Template which sits in a grid with other timepickers and numeric text boxes. Only thing with this way of working is that once the script is fired, the numeric boxes used this script also to validate (hence the return $.isNumeric(input.val()) line. Hope this helps someone else out.
TimePickerFor Control:
#using Kendo.Mvc.UI
#model DateTime?
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Format("HHmm")
.HtmlAttributes(new{data_format="HHmm"})
.ParseFormats(new[]{"HHmm"})
)
<script>
var originDate = kendo.ui.validator.rules.mvcdate;
kendo.ui.validator.rules.mvcdate = function(input) {
var format = input.attr("data-format");
if (input.val() == "") {
return kendo.parseDate("0000", format);
}
if (format) {
return kendo.parseDate(input.val(), format);
} else {
return $.isNumeric(input.val());
}
};
</script>
I think you have to remove the curly braces and make sure that is a valid format type. I also don't think the 0 is necessary.
Here's some formating documentation
http://docs.telerik.com/kendo-ui/getting-started/framework/globalization/dateformatting
#(Html.Kendo().TimePickerFor(m=>m)
.Value(#Model)
.Min("05:00")
.Max("00:00")
.Format("yyyy/MM/dd hh:mm tt")
)
Edit:
Is your max and min values correct? I don't see how that is logically correct.
Related
I have an few editorfor in my view like following
#Html.EditorFor(Model => Model.CashBalance)
Now when i enter any value in to that editorfor,the value should change to currency value in textbox change event
For ex:
123 should display as 123.00
14.35 should display as 14.35
I want to do this in generic way so that I don't need to change it every where as my project has many editorfor which takes inputs from user.
As I am using an EditorTemplate for all these textboxes,i want to handle here itself.
My EditorTemplate for this is decimal.cshtml and it looks like the foll
#model decimal?
#{
string value = (Model.HasValue == false || Model.Value == 0) ? "" : string.Format("{0:0.00}", Model.Value);
}
#Html.TextBox(
"",
value,
new { #class="amountRightAlign"}
)
Will there be any textchange event i can write here so that it affects where ever there is decimal datatype?
Thanks in advance?
Html helpers are server side code used to generate the html which is sent to the client. In order to interact with user changes in the browser, you need to use javascript to handle events.
In your case you don't need an EditorTemplate. Instead, just the overload of TextBoxFor() that accepts a format string
#Html.TextBoxFor(m => m.CashBalance, "{0:0.00}", new { #class="decimalnumber" })
Then in the view, or in a separate script file
$('.decimalnumber').change(function () {
var num = new Number($(this).val());
if (isNaN(num)) {
// Its not a valid number
return;
}
$(this).val(num.toFixed(2));
})
I am using Kendo Grid (version 2014.1.318) with inline editing on "de-DE" culture. So the numbers should use a comma(,) as the decimal separator, eg: 79,5.
The Numeric Text Box in the grid is displaying the expected format when in "Edit" mode. No problem here. But when I click on "Update" button, it is sending "79.5" instead of "79,5" back to my server. My server is configured with the "de-DE" culture and the ModelBinder couldn't process numbers in that format and as a result, assigned ZERO to my variable.
Is this a known bug or am I missing something? Everything is fine when i use "en-US" culture or any culture that uses period(.) as its decimal separator.
Did you include the kendo.culture.de-DE.min.js file:
Did you change the kendo culture:
kendo.culture("de-DE");
At last you can also try to change the culture in the numeric text box:
#Html.Kendo().NumericTextBox().Culture("de-DE")
We are having the same problem for a year now. It seems it's on low priority for Telerik to solve this or we missed the solution.
This is how we solved it:
Pass this function to the data function of grid create and update like here:
.Update(update => update.Action("Update", "Gradings").Type(HttpVerbs.Put).Data("convertDecimals")))
function convertDecimals(data) {
for (var property in data) {
var value = data[property];
if (typeof value === "number") {
// if the number is integer
if (value % 1 == 0) {
data[property] = value.toString();
}
else {
data[property] = kendo.toString(value, "n");
}
}
}
}
and this on edit:
.Events(events => events.Edit("replaceDecimalSign"))
function replaceDecimalSign(data) {
var value = $(data).val();
var converted = value.toString().replace('.', ',');
$(data).val(converted);
}
Also you need the correct culture settings like alreay answered by MohQut.
kendo.culture("de-DE");
I am developing a MVC app. I have some amount fields. by default it showing numbers without comma separation. for e.g. if I have amount 500000000 then I want to display it like 50,00,00,000 I want to show in Indian currency format,in indian format first comma comes after 3 digits then for every 2 digits comma appears.
How to do this ?
I have tried this , but giving an error...
#{
System.Globalization.CultureInfo Indian = new System.Globalization.CultureInfo("hi-IN");
}
#(String.Format(Indian, "{0:N}", modelItem => item.SanctionedAmount))
}
Solved, Thanks to Darin Dimitrov, Answer Is :
#{
var indianCulture = new System.Globalization.CultureInfo("hi-IN");
#string.Format(indianCulture, "{0:N}", item.SanctionedAmount)
}
You seem to have passed some lambda expression to the string.Format function (modelItem => item.SanctionedAmount), but this function doesn't take any delegates.
Try like this:
#{
var indianCulture = new System.Globalization.CultureInfo("hi-IN");
#string.Format(indianCulture, "{0:N}", item.SanctionedAmount)
}
In the same context the following also works if you put in Index.cshtml
<td>#item.Total_Payments.ToString("N")</td>
How can I set both default decimal and thousands separator for formatting number in asp.net mvc regardless of culture?
You could create a DisplayTemplate that would handle how numbers like this are displayed in your views:
/Views/Shared/DisplayTemplates/float.cshmtl:
#model float
#string.Format("{0:N2}", Model);
and then you can call it like this from your views, if Amount was of type float:
#Html.DisplayFor(m => m.Amount)
To control the thousands separator you'll have to apply your changes to the NumberFormat for the current culture.
If you want this to happen regardless of the current culture you can simply clone the current culture, apply your modified NumberFormat and set it as the current one.
In an MVC app you would typically do this during Application_BeginRequest
protected void Application_BeginRequest(object sender, EventArgs e)
{
newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.NumberGroupSeparator = "~";
System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;
}
Now you can use the 'normal' formatting options of ToString() to further control the formatting according to your needs:
var a = 3000.5;
var s = a.ToString('N:2') // 3~000.50
s = a.ToString('N:4') // 3~000.5000
You need to specify a custom number format in order to achieve what you are looking for. Here is the MSDN on creating custom string formatting functions.
If you really need a custom thousands separator, create your own NumberFormatInfo variable assigning the values that you want to the thousands separator (and the decimal if so needed). Then apply the custom format to your number.
var numberFormatter = new CultureInfo( "en-US", false ).NumberFormat;
numberFormat.NumberDecimalSeparator = ";";
numberFormat.NumberGroupSeparator = "-";
var myNumber = 1234567.89;
var myFormattedNumber = myNumber.ToString("#,###.##", numberFormatter);
//myFormattedNumber -> 1-234-567;89
Some information on the NumberFormat class from the MSDN
variable.ToString("n2") - This worked for me in ASP.Net MVC Razor.
string.Format("{0:N2}", yourLovelyNumber);
I will post the code that finally worked for me. On controller, on OnActionExecuting function:
ViewBag.CurrentNumberFormat = new System.Globalization.CultureInfo("en-US", false).NumberFormat;
ViewBag.CurrentNumberFormat.NumberDecimalDigits = 2;
ViewBag.CurrentNumberFormat.NumberDecimalSeparator = "~";
ViewBag.CurrentNumberFormat.NumberGroupSeparator = " ";
and in View:
#((1234567.435).ToString("#,###.##", ViewBag.CurrentNumberFormat))
I had the same issue and can recommend autoNumeric plugin https://github.com/autoNumeric/autoNumeric
Include plugin:
<script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
Html:
<input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control">
Script:
<script>
jQuery(function($) {
$('#DEMO').autoNumeric('init');
});
</script>
You can type only number, if you type 100000,99 you will see 100.000,99.
When I print the created_at field of a model using Backbone.js( <i> {{created_at}} </i>
), I'm getting: 2011-08-07T12:03:00Z.
I'm trying to change the date to a readable format for hours and I'm not being able to.
I want the T and Z to be removed before printing.
thanks
Change the variable in your template context, or add a new one. I would add a new one.
If this is in your render function, it may be changed to something like this:
render: function() {
var context = this.model.toJSON();
context['created_at_formatted'] = this.formatDate(context['created_at']);
var html = this.template.to_html(context);
$(this.el).html(html);
}
With a function added to the view like this:
formatDate: function(d) {
var pad = function (n) {
return n < 10 ? '0' + n : n;
};
// in case the date is a string; you can remove this if you know it will be a date
if (typeof date === 'string') {
d = new Date(d);
}
return [
d.getUTCFullYear(), '-',
pad(d.getUTCMonth() + 1), '-',
pad(d.getUTCDate()), ' ',
pad(d.getUTCHours()), ':',
pad(d.getUTCMinutes()), ':',
pad(d.getUTCSeconds())
].join("");
}
Then the template would be like this:
<i> {{created_at_formatted}} </i>
To simplify the date formatting function, you could also use a date formatting library like DateJS. You could also move the date formatting to the model.
Readable? Why not jQuery timeago?
jQuery timeago
In your Backbone model,
toTemplateData: ->
_.extend
created_duration: do => $.timeago #get("created_at") if #get("created_at")
In your Backbone view,
render: ->
#$el.html(#template(#model.toTemplateData() ))
In your template,
<time title="{{created_duration}}"></time>
You can use the strftime on your created_at
<i> {{created_at.strftime('%Y/%m/%d')}} </i>
Ben's answer is correct but the formatting of the date should really be in a model somewhere as it is business logic.
My variation of that would be:
render: function() {
var context = this.model.format().toJSON();
var html = this.template.to_html(context);
$(this.el).html(html);
}
And in your model, something like:
format() {
this.set('created_at_formatted', formatDate(this.get('created_at')));
return this;
}
formatDate: function(d) {
// format date stuff (See Ben`s answer)
return d;
}
And your template would render:
<i> {{created_at}} </i>
This removes some redundancy, promotes reuse and it is easier to read. Perhaps my answer needs a little work but hopefully you get the general idea.