Format a DateTime in a MVC Template - internationalization

Using the example from Kendo's ComboBox: (ASP.NET MVC | template.cshtml)
#(Html.Kendo().ComboBox()
.Name("customers")
.DataTextField("ContactName")
.DataValueField("CustomerID")
.HtmlAttributes(new { style = "width: 400px" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCustomers", "Home");
});
})
.Filter("startswith")
.Height(300)
.Template("<img src=\"" + Url.Content("~/Content/web/Customers/") + "${data.CustomerID}.jpg\" alt=\"${data.CustomerID}\" />" +
"<dl>" +
"<dt>Contact:</dt><dd>${ data.ContactName }</dd>" +
"<dt>Company:</dt><dd>${ data.CompanyName }</dd>" +
"</dl>")
)
Inside the Template if you want to use a value that is a DateTime, for example ${ data.StartDate } you would end up with something like this: 2012-06-13T00:00:00
What would the syntax be to format that to a readable Date inside that Template?

The quick and dirty solution would be to create a new property that outputs your date as a string.
The more correct solution would be to feed the output of the property to a javascript date formatting function. You could use something like date.js.
Add this code:
"<dt>StartDate:</dt><dd>" + Date.parse('${ data.StartDate}').toString("M/d/yyyy") + "</dd>" +

The best solution to your date formatting would be to create a DisplayTemplate at Views/Shared/DisplayTemplates/DateTime.cshtml
#model DateTime
#String.Format("{0:dd/MM/yyyy}", Model))
that would change it universally
source

Related

kendo mvc ajax grid sending Viewbag or ViewData variable as a parameter in client Template Column

I'm using Telerik Kendo MVC Grid ,and i need to use client template as a link.
The Question is : How to send ViewBag Variable or ViewData as a parameter within the link?
Just the syntax for creating a ClientTemplate using a ViewBag field?
#{
ViewBag.Data = "kendo-mvc-ajax-grid-sending-viewbag-or-viewdata-variable-as-a-parameter-in-clien";
}
#(Html.Kendo().Grid<GridViewModel>()
.Name("grid")
.Columns(cols =>
{
cols.Bound(c => c.Field1);
cols.Bound(c => c.Field2);
cols.Bound(c => c.Field2);
.ClientTemplate(
"<a href='http://stackoverflow.com/questions/40106180/" + ViewBag.Data + "' target='_blank'>Click Here</a>" );
})
}
...rest of grid config....
)
Otherwise, you need to provide more specific details of what you are asking.

kendo grid foreign column selected text being overrriden by client template

I have a kendo grid on MVC proeject with a foreignKey column with a client template on the same column to send the data to the controller (hidden) as I have a header information just above the kendo grid that i want to send to the controller. Everything works fine. But when I select the dropdown in the grid it displays the value rather than the text.
columns.ForeignKey(c => c.studentId, (System.Collections.IEnumerable)ViewData["Students"], "Id", "name")
.Title("id - name")
.Width(70)
.ClientTemplate("#= studentId #" + "<'input type='hidden' name='MyModel[#= index(data)#].StudentId' value='#= StudentId #' />");
The above is the exact code I currently have.
How can I show the user the selected text (name in this case) rather than the value(Id in this case) on the kendo grid.
Thanks
just had the same problem and found this on the telerik site:
Basically create a function that looks up the text from Foreign Key Drop Down in the grid.
columns.ForeignKey(c => c.G_ID, plus, "Value", "Text").Title("Plu").Lockable(true).ClientFooterTemplate("Total").ClientTemplate("#= getTextByValue(data)#" +
"<input type='hidden' name='Schedules[#= index(data)#].G_ID' value='#= G_ID #' />"); //.Hidden();
and the javascript:
var collection;
And the function:
function getTextByValue(data) {
console.log(data);
var dGrid = $("#the-dtl-grid").data("kendoGrid");
//change the index of the column with your index
valuesCollection = dGrid.options.columns[1].values;
//if the collection is empty - get it from the grid
if (!collection) {
collection = {};
//Set the correct FKColumn index
for (var value in valuesCollection) {
collection[valuesCollection[value].value] = valuesCollection[value].text;
}
}
return collection[data.G_ID];
}
Thanks, very helpfull. Just in my case I must change this row valuesCollection = dGrid.options.columns[1].values; to valuesCollection = dGrid.columns[1].values;

Format Date type using a function in Kendo Grid

I have a function for date conversion, that accepts a datetime argument and returns string. How can I use this function to format Date columns in a Kendo Grid?
I've tried the following codes, and none of them worked
columns.Bound(x => x.ModifyDate).ClientTemplate(#Utility.GetPersianDate((DateTime)"#: ModifyDate #"));
columns.Bound(x => x.ModifyDate).Template(#<text>#Utility.GetPersianDate((DateTime)#item.ModifyDate)</text>);
columns.Bound(x => x.ModifyDate).Format(#Utility.GetPersianDate(Convert.ToDateTime("#: ModifyDate")));
I've also tried to convert it on the server side, but it's not possible, since the formatted date is not recognized as a valid date. It's not important, because it's just for display. Users are not supposed to change or enter that date. If nothing works, I might consider using string instead of DateTime and convert it on the server.
There are several reasons why your code doesn't work.
columns.Bound(x => x.ModifyDate).ClientTemplate(#Utility.GetPersianDate((DateTime)"#: ModifyDate #"));
This isn't working because the server code runs first, so "#: ModifyDate #" can't be converted to a DateTime. It should be InvalidOperationException or something.
columns.Bound(x => x.ModifyDate).Template(#<text>#Utility.GetPersianDate((DateTime)#item.ModifyDate)</text>);`
The second line doesn't work because of a strange Template call. It should be called like this: .Template(item => Utility.GetPersianDate(item.ModifyDate))
and it will do the job unless you're using Ajax binding, in which case you cannot use Template method.
columns.Bound(x => x.ModifyDate).Format(#Utility.GetPersianDate(Convert.ToDateTime("#: ModifyDate")));`
The third line doesn't work because Format should be called like Format("{0:D}"), and it can't accept any other arguments.
So if you're not using Ajax binding, the correct Template call should do the trick. If you do, than you can either convert it on the server-side or write a Javascript function to convert date to persian and call it in ClientTemplate like this: .ClientTemplate("# convertToPersian(ModifyDate) #")
I personally recommend you to do it on server-side like this:
public class SomeView
{
public DateTime ModifyDate { get; set; }
public string ModifyDatePersian { get { return Utility.GetPersianDate(ModifyDate); } }
}
and use it on client-side like this: .ClientTemplate("#: ModifyDatePersian) #").
Actually you can use Kendo it's own parse/format function, in short example:
#(Html.Kendo().Grid(Model.dummyHistoryList)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(model => model.dueDate).ClientTemplate("#= kendo.toString(kendo.parseDate(dueDate),'dd MMM yyyy') #");
columns.Bound(model => model.DueItem);
columns.Bound(model => model.dueAmount).Format("{0:#,##0.00}").HtmlAttributes(new { style = "text-align:right" });
})
.Pageable()
//and so on....
)
To override a JQuery validation:
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
//Here I use kendo parse to validate the format
//you want or you can make your own/implement your
//validation code below here. (Example)
if ((kendo.parseDate(value, "dd/MM/yyyy")) == null){
ok = false;
}
//END
return ok;
});
});
</script>
Read additional format to KendoUI DatePicker. Simply add the parseFormat:
.ParseFormats(new List<string> { "yyyy-MM-dd", "MM-dd-yyyy", "dd-MM-yyyy" })//So On...

mvc3: Multiline Text area with value defined in the view

I am want to have a text area with multiple lines and a value in MVC3. I can't seem to define a textareafor or an editorfor that has a #Value attribute which I can set. I want to have something like
#Html.TextAreaFor(x => x.model, 10, 15, new{#Value="try"})
Also, I want to be able to do this in the view because the default value will depend on an attribute of another model used within the same view.
Any thoughts please.
The textarea html element does not support the value attribute. So you can't set its value using #Html.TextAreaFor.
So what you have to do is this:
#model MvcApplication.Models.Model
#{
if (1 > 2) // your logic here
{
Model.Description = "value1";
}
else
{
Model.Description = "value2";
}
}
#Html.TextAreaFor(model => model.Description, new { #rows = "10", #cols = "15" })
Let the html helper handle the rendering.
Use Telerik control
Html.Telerik().EditorFor(model => model.Description)
.Name("Editor")
.HtmlAttributes(new { style = "height:400px" })
.Encode(false)
.Value((String)ViewBag.Contents)
.Render();

ASP.NET MVC 3 WebGrid - Conditional Column Formatting

Is there anyway to do conditional formatting with Webgrid in ASP.NET MVC 3?
I know I can say:
... grid.Column("PropertyName", "Header Name", style: "bold") ...
and it will render HTML that for the TD that says: class="bold".
What I want, is to render some TDs in one style and other TDs in another style. Like:
... grid.Column("PropertyName", "Header Name", style: (item) => (item.Property > 100) ? "bold" : "normal")) ....
but this causes the error "Best overloaded method match ... has some invalid arguments."
Any idea if this is possible?
Thanks
.Jim Biddison
I know I'm kind of late with the answer, but if someone is still looking for that kind of conditional formating / column value binding for WebGrid here's somehting that works :
#grid.GetHtml(
columns: grid.Columns(
grid.Column(format: (item) => (item.someproperty !=null) ?
Html.Raw("I've got value") :
Html.Raw("I don't :("))
)
)
You can do this with some JQuery:
<script type='text/javascript'>
$(document).ready(function () {
jQuery.each($('tbody tr td'), function () {
if (this.textContent == "some value") {
$(this).addClass("some class");
}
});
});
</script>
Of course, you'll have to modify the logic inside the each loop...
Hope that helps.
I don't think the style property accepts functions. You can use jQuery or here is a hack:
Hack
For googler, an improved version of the Torm answer:
#grid.GetHtml(
columns: new[]
{
grid.Column(format:item => Html.Raw("<span" + (item.Property > 100 ? " style='bold'" : "") + ">" + item.Property + "</span>")),
}
)

Resources