Date field inside Kendo Grid is null on controller - javascript

The following code works fine on development, but when we deploy to production the field fecha(initally datetime) gets null.
We even tried changing to string instead of datetime and it still doesnt work on our customer servers
Our partial view is like this:
fecha.chstml
#using xx.Relacionamiento.Modelo.Bussiness.Entities
#model EventoEducacionFecha
#using Kendo.Mvc.UI
<script type="text/javascript">
$(function () {
kendo.culture("es-CO");
})
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
function getFecha() {
debugger
var fecha = $("#FechaEvent").val();
return {
FechaEvent: fecha
};
}
</script>
#(Html.Kendo().Grid<EventoEducacionFecha>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.EventoEducacionFechaId).Hidden();
columns.Bound(p => p.FechaEvent).Title("Fecha Evento").ClientTemplate("#= kendo.toString(kendo.parseDate(FechaEvent, 'yyyy-MM-dd'), 'MM/dd/yyyy') #");
columns.Bound(p => p.HoraInicio);
columns.Bound(p => p.HoraFin);
columns.Command(command =>
{
command.Edit().Text("Editar");
//command.Destroy();
command.Custom("Borrar").Click("openWindowConfirmDelete").HtmlAttributes(new { data_NomCol = "FechaEvent" });
}).Width(250).Title("Acciones");
})
.ToolBar(toolbar => toolbar.Create().Text("Agregar Fecha"))
.Editable(editable => editable.Mode(GridEditMode.InLine).DisplayDeleteConfirmation(false))
.Pageable()
.Sortable()
.Scrollable()
//.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.EventoEducacionFechaId);
model.Field(a => a.EventoEducacionFechaId).Editable(false);
model.Field(a => a.FechaEvent).Editable(true);
model.Field(a => a.HoraInicio).Editable(true);
model.Field(a => a.HoraFin).Editable(true);
})
.Create(update => update.Action("Fechas_Create", "EventosEducacion").Data("getFecha"))
.Read(read => read.Action("GetFechas", "EventosEducacion").Data("getDatoEventoId"))
.Update(update => update.Action("Fecha_Update", "EventosEducacion"))
.Destroy(update => update.Action("Fecha_Destroy", "EventosEducacion"))
)
)
This is PART of the view that uses the partial view
<div class="row oculto" id="VerFecha">
<div class="col-md-12">
<div class="form-group">
<div id="mostrarFecha_div"></div>
#*#Html.Partial("~/Views/EventosEducacion/Fechas.cshtml",null,null)*#
</div>
</div>
And this is the controller action
//[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Fechas_Create([DataSourceRequest] DataSourceRequest request, EventoEducacionFecha EducaFecha, string FechaEvent)
{
if (EducaFecha.FechaEvent != null && EducaFecha.HoraInicio != null && EducaFecha.HoraFin != null)
{
LstEventoEducacionFecha.Add(new EventoEducacionFecha {
EventoEducacionFechaId = Guid.NewGuid(),
EventoId = Guid.Empty,
HoraFin = EducaFecha.HoraFin,
FechaEvent = DateTime.Parse(FechaEvent),
HoraInicio = EducaFecha.HoraInicio,
});
EducaFecha.EventoEducacionFechaId = LstEventoEducacionFecha.OrderBy(o => o.EventoEducacionFechaId).Select(s => s.EventoEducacionFechaId).FirstOrDefault();
return Json(new[] { EducaFecha }.ToDataSourceResult(request));
}
return Json(new[] { EducaFecha }.ToDataSourceResult(request));
}

In the past, I have had issues with Kendo's library and anything related to DateTime. You usually have to convert the DateTime that you are sending your controller from JavaScript's UTC time format to something that c# understands. Otherwise, send it as a string and see if it's still null or empty. I have a feeling it will send something over as a string and you can convert it on the server side.
In the past for a Kendo DateTime Picker, I have had to do the following client side in js:
var meetDatePicker = $("#MeetingDate").data("kendoDatePicker");
var mDate = new Date(meetDatePicker.value());
var meetDate = mDate.toUTCString();
Then pass the meetDate to my controller as a string, and on the server-side in c#:
DateTime meetDateConv = DateTime.Parse(meetingDate);

I have had similar problems, everything works fine on my side but on the client side things break. My solution is to check the Regional settings of the computer and check if the date format used is correct.

Your grid is bound to a EventoEducacionFecha model, which contains a FechaEvent field.
Your controller action is receiving the EventoEducacionFecha model AND a string called FechaEvent.
When the grid row is posted, the FechaEvent column value gets bound to the EventoEducacionFecha.FechaEvent field and is not bound to the separate FechaEvent string parameter as it has already been bound.
The model binder stops binding a posted value after the first match it finds and does not bind to all matching fields/parameters.
If you rename the FechaEvent field in getFecha() and rename the string parameter in your controller action to match, your should start getting a value.
I suppose the order of binding may be changed slightly between debug and release but I've not seen that personally...whenever I "duplicated" field/parameter names in my controller action, it has not worked in both configurations.

Related

filter data in Kendo grid by connect to a method asp.net MVC

I am making a code using ASP.NET MVC with kendo grid.
I want to bring the data from database to Kendo grid which equal to specific date or by default "today".
I want to make a datepicker and a button at the toolbar and everytime I click the button it send a request to the control and filter the data in LINQ and send the request for all the data in one day. I wrote this code:
Controller class:
//main method
public ActionResult LogAdminList()
{
return View();
}
//submethod for grid
public ActionResult Grid_ReadLogAdminList([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "id")] string date)
{
DateTime _temp;
if (!DateTime.TryParse(date, out _temp))
_temp = DateTime.Now;
return Json(_context.Entities<LogAdmin>().NoTracking().OrderByDescending(l => l.TimeStamp)
.Where(f => DbFunctions.TruncateTime(f.TimeStamp) == DbFunctions.TruncateTime(_temp))
.Select(l => new LogAdminInfo
{
Id = l.Id,
Message = l.Message,
MessageTemplate = l.MessageTemplate,
Level = l.Level,
TimeStamp = l.TimeStamp,
Exception = l.Exception,
Properties = l.Properties,
LogEvent = l.LogEvent,
})
.ToDataSourceResult(request));
}
the kendo code is :
#(Html.Kendo().Grid<LogAdminInfo>()
.BindTo(Model)
.Name("LogAdminList")
.Sortable()
.Columns(columns =>
{
columns.Bound(p => p.Message).Width(50).Title(WebResources.LogListMessage);
columns.Bound(p => p.MessageTemplate).Width(50).Title(WebResources.LogListMessageTemplate);
columns.Bound(p => p.Level).Title(WebResources.LogListLevel);
columns.Bound(p => p.TimeStamp).Title(WebResources.LogListTimeStamp).Format("{0:dd.MM.yyyy H:mm}");
columns.Bound(p => p.Exception).Width(50).Title(WebResources.LogListException);
columns.Bound(p => p.Properties).Width(50).Title(WebResources.LogListProperties);
columns.Bound(p => p.LogEvent).Title(WebResources.LogListLogEvent);
})
.Pageable(pageable => pageable
.Refresh(true)
.ButtonCount(5))
.HtmlAttributes(new { #class = "grd_UpcomingMilestone" })
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
<label class="category-label" for="category">#WebResources.LogFilterMessage</label>
#(Html.Kendo().DatePicker()
.Name("datepicker")
.Value(DateTime.Today)
.Format("dd.MM.yyyy")
)
#(Html.Kendo().Button()
.Name("filterButton")
.Icon("filter")
.Content("Filter")
.HtmlAttributes(new { type = "button" })
)
</div>
</text>);
})
.DataSource(source => source
.Ajax()
.Batch(true)
.ServerOperation(false)
.PageSize(100)
.Read(read => read.Action("Grid_ReadLogAdminList", "LogAdmin").Data("getFilterDate"))
))
I don't know what to do exactly in the javascript. the code works fine in the first request but not when I filter.
what should I write as a javascript?
thank you very much.
You have to pass data from client to server using getFilterDate function specified in you Kendo Grid Read Data method. Implement a function like this. The return type must be an object with fields with the same name you defined in your MVC Action, in this case date. Kendo will serialize them in order to build the get request:
function getFilterDate() {
var mydate = $("#datepicker").data("kendoDatePicker").value();
return {
"date": mydate
}
}

How to refresh a kendo ui grid inside a partial view without reloading the entire page?

Good day,
I am having a tough time refreshing just the kendo grid that is placed inside a partial view. Take a look at the code I am currently using in my partial view:
#model IEnumerable<TelerikMvcAscernAdmin2.Models.ConnectionViewModel>
#(Html.Kendo().Grid(Model).Name("id").Sortable().Columns(c => {
c.Bound(p => p.SystemId);
c.Bound(p => p.Host);
c.Bound(p => p.Port);})
.DataSource(datasoure =>datasoure.Server().PageSize(25).Sort(sort=>{sort.Add(c => c.Host).Ascending(); })
).Filterable()
.Pageable(p => p.PageSizes(new int[] { 25, 35, 40 })
.Refresh(true)).Groupable().Sortable().Scrollable(s => s.Height("200px")).RowAction(row => {
if (row.DataItem.Port == 0) row.HtmlAttributes["style"] = "background:red"; }).HtmlAttributes(new { style = "width: 800px;" }) )
<script> $(document).ready(function () {
var refId = setInterval(function () {
var grid = $("#id").data("kendoGrid");
grid.dataSource.read();
}, 40000);
}); </script>
As you can see, I am using a server side function so that I can auto-refresh this grid. I have tried switching it to an Ajax function, but when I do that my grid can't be refreshed.
I am rendering this partial view inside my Home view, as shown below:
#Html.Action("EngineConnection", "GatewayConnections")
Also, take a look at my action controller method, I am returning all my data to a partial view:
public ActionResult EngineConnection()
{
var gatewayConnections = GatewayConnections.GetAllConnections();
var agents = Agent.RetrieveAgents();
var connectionViewModels = (from agent in agents.Where(a => a.Active)
join gatewayConnection in gatewayConnections on agent.SystemId equals gatewayConnection.ClientId into
agentConnections
from agentConnection in agentConnections.DefaultIfEmpty()
select
new ConnectionViewModel
{
SystemId = agent.SystemId,
Host = (agentConnection == null ? string.Empty : agentConnection.Host),
Port = (agentConnection == null ? 0 : agentConnection.Port)
}).ToList();
return PartialView("_EngineConnection", connectionViewModels);
}
I have tried returning a JSON object, but that does not seem to do the trick. Is there a way to refresh just the grid, instead of the entire page, and still keep the grid inside the partial view?
Any suggestion will help!
Thanks
I would suggest you following way to bind the grid.
#(Html.Kendo().Grid<EntityStandardGridModel>()
.Name("KendoEntityStandardGrid")
.Columns(columns =>
{
//columns
})
.Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
.Sortable(sortable => sortable.AllowUnsort(false))
.Scrollable(scrollable => scrollable.Virtual(true))
.Resizable(resizable => resizable.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(100)
.Model(model => model.Id(p => p.SearchId))
.Read(read => read.Action("GetStandardGriddata", "Search", new { SearchId = Model.SearchId }))
)
)

Kendo UI Grid get id of current element javascript

i m using Kendo UI apsnet and i have a Gird with autocomptele as template in 3rd column and i want send data using javascript function "onAutoCompleteX", in this function i want to get id of active autocomplete to send text as parametere to action "GetArticle" but my probleme is how get this id, tried many methods always i get "undefined" or error
#using KendoUIMvcApplication2.Areas.Gescom.Models.Achat
<style>
.k-widget .templateCell
{
overflow: visible;
}
</style>
<script>
function initMenus(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
function onAutoCompleteSelectX(e) {
var dataItem = this.dataItem(e.item.index());
var url = '#Url.Action("GetArticle", "Fiche")';
$.ajax({
url: url,
data: { code: dataItem.Code }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
if (data == null)
document.getElementById('labelx').innerHTML = "null";
else
document.getElementById('labelx').innerHTML = data.Code;
},
error: function () {
document.getElementById('labelx').innerHTML = "error";
}
});
}
function onAutoCompleteX() {
var currentId = $(this).attr('id');
//var currentId = $(this).id;
//document.getElementById('labelx').innerHTML = $(this).className; //$obj.attr('id');
return {
text: document.getElementById(currentId).value
//text: $("#id_of_another_autocomplete").val() works fine when i set static id manually
};
}
</script>
<div class="lines-tab-doc">
#(Html.Kendo().Grid<LineAppelOffre>()
.Name("grid-lines-doc")
// Declare grid column
.Columns(columns =>
{
// Cretae all the columns base on Model
columns.Bound(l => l.Document);
columns.Bound(l => l.LigneOriginale);
columns.Template(l => { }).Title(#Resources.Resource.Article)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(
Html.Kendo().AutoComplete()
.Name("Article")
.HtmlAttributes(new { id = "#=LigneOriginale#", style = "width:100%;" })
.DataTextField("Code")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetArticles", "Fiche").Data("onAutoCompleteX");
})
.ServerFiltering(true);
})
.Events(e => { e.Select("onAutoCompleteSelectX"); }).ToClientTemplate().ToHtmlString()
);
columns.Bound(l => l.Fournisseur);
columns.Bound(l => l.RefArtFrs);
// Edit and Delete button column
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
})
.Events(ev => ev.DataBound("initMenus"))
// Declare ajax datasource.
// CRUD operation are wired back to ASP MVC Controller/Action e.g. HomeController, GetAll
// Set the model Id
.DataSource(datasoure => datasoure.Ajax()
.Model(model =>
{
//model.Id(l => l.Document);
model.Id(l => l.LigneOriginale);
})
.Read(read => read.Action("LinesAppelOffre_Read", "Achat"))
.Create(create => create.Action("LinesAppelOffre_Add", "Achat"))
.Update(update => update.Action("LinesAppelOffre_Update", "Achat"))
.Destroy(delete => delete.Action("LinesAppelOffre_Delete", "Achat"))
.PageSize(10)
)
// Add tool bar with Create button
.ToolBar(toolbar => toolbar.Create())
// Set grid editable.
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable(scr=>scr.Height(327))
.Sortable()
.Selectable()
.Navigatable()
.Pageable(pageable =>
{
pageable.Refresh(true);
pageable.PageSizes(true);
pageable.Messages(msg => msg.Empty(null));
})
)
</div>
You can get your AutoComplete id like that:
function onAutoCompleteX(e) {
var currentId = e.sender.element.attr('id');
...
}
But I'm not sure if you have explicity set name as "Article" .Name("Article") you will not always get "Artilcle" as id, even if you set it using .HtmlAttributes property.
If so, just try to use different attribute then id and get is same way.
i used document.activeElement
Browser compatibility
Chrome 2
Firefox (Gecko) 3.0
Internet Explorer 4
Opera 9.6
Safari 4.0

Access row data from within a ClientTemplate within a ClientDetailTemplate

I'm using a Kendo UI Web Grid in an ASP.Net MVC 4 application.
At the bottom of the code below you'll see a JavaScript function called GetEditChildUrl that accepts a parameter called data. Unfortunately, what gets passed in as the data parameter is the parent row data but I was expecting the child row data. This works fine for GetEditParentUrl. So how do I get the child row data?
#(Html.Kendo().Grid<Application.Models.Parent>()
.Name("grid_parent")
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditParentUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.Scrollable(action => action.Virtual(true))
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Parents_Read", "Parent"))
)
.Scrollable(s => s.Height("auto"))
.ClientDetailTemplateId("client-template")
)
#section Scripts {
<script id="client-template" type="text/x-kendo-template">
<h3>Contacts</h3>
#(Html.Kendo().Grid<Application.Models.Child>()
.Name("grid_child_#=Id#") // make sure the Name is unique
.Columns(columns =>
{
columns.Bound(x => x.Name);
columns.Bound(x => x).ClientTemplate(
"<a href='#= GetEditChildUrl(data) #' class='k-button' style='min-width:0px;'><span class='k-icon k-i-pencil'></span></a>"
).Width(90).Filterable(false);
})
.DataSource(dataSource =>
dataSource.Ajax().Read(read => read.Action("Children_Read", "Parent", new { parentId = "#=Id#" }))
)
.Scrollable(s => s.Height("auto"))
.Sortable()
.ToClientTemplate()
)
</script>
<script>
function GetEditParentUrl(data) {
return "#Url.Action("Edit", "Parent")/" + data.Id;
}
function GetEditChildUrl(data) {
return "#Url.Action("Edit", "Child")/" + data.Id;
}
</script>
}
Try escaping the hash (#) symbols in your column client template.
columns.Bound(x => x)
.ClientTemplate("<a href='\\#= GetEditChildUrl(data) \\#' ...>")
From the KendoUI docs:
Important: The "#" characters used for a template expression should be
escaped when using a column ClientTemplate in a detail template so
that the expression is evaluated in the correct context.

Use Javascript function into Kendo Grid Template

I want to use Javascript Function in Kendo Grid Create.
For that I have defined the Javascript Function as,
<script>
function GetCompanyID()
{
return $("#Company").val();
}
</script>
And I want to use it in Create template of Kendo Grid as,
#(Html.Kendo().Grid<Invoice.Models.ViewModels.DossierViewModel>()
.Name("Dossier")
.Columns(columns =>
{
columns.Bound(p => p.CustomerName).Title("Customer").Width(150);
columns.Bound(p => p.InvoiceNumber).Title("INV no.").Width(100);//.Width(20);
columns.Bound(p => p.InvoiceAmountLC).Title("INV Amount LC").Width(150);
})
.ToolBar(toolbar => toolbar.Create().Text("Add New Dossier"))
.Editable(ed => ed.Mode(GridEditMode.PopUp).TemplateName("New_Dossier")) //Having Different Template for New Dossier
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model => { model.Id(p => p.DossierID); })
.Read(read => read.Action("Dossier_Read", "Dossier"))
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
.Filter(filters =>
{
// Show products whose ProductName property contains "C"
filters.Add(dossier => dossier.Status).Contains("");
})
)
)
In that I want to use that Javascript functio as I am currently using in Above code as,
.Create(create => create.Action("Dossier_Create", "Dossier", new { #CompanyID = GetCompanyID }))
But this is not the Way it should be used. Please Help me on this. How can I use that Javascript function into this, ASAP.
You need to use the Data() method of the grid data source to send this data. Something like:
.Create(create => create.Action("Dossier_Create", "Dossier").Data("GetCompanyID")
function GetCompanyID()
{
return {
CompanyID: $("#Company").val();
};
}
Check the grid FAQ for more info and an example.

Categories

Resources