Telerik MVC Grid Popup Default Values - asp.net-mvc

I have a Telerik MVC Grid with a custom editable popup template
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.Window(w => w.Width(600))
.TemplateName("Inspection")
)
The template is based on a model, and contains two drop down lists
#(Html.Kendo().DropDownListFor(model => model.InspectionStatus)
.BindTo(new List<SelectListItem>()
{
new SelectListItem() { Text = "Fail", Value = "0" },
new SelectListItem() { Text = "Pass", Value = "1" }
})
)
and
#(Html.Kendo().DropDownListFor(model => model.CloseoutStatusID)
.DataValueField("LookUpID")
.DataTextField("LookUpText")
.DataSource(source => {
source.Read(read => { read.Action("Get", "LookUp", new { LookUp = "CloseOutStatus" }); });
})
)
I need to set the default values for both fields... Currently they both come back as 0 regardless of what I have done.
So far I've:
Tried setting the default value attribute
Set the values in the model's constructor
Set the .Value() to what the default should be.
Everything else is working correctly... I can select a bound item and it returns the correct value. I can edit an existing item and it shows the proper data in the template. I can saved edited data and it returns the correct value.
Any reliable documentation would be greatly appreciated.

Received the answer on the telerik forums.
The telerik grid create action in the toolbar uses the model information in the data source.
by adding the fields to the model and setting the default value there I was able to get the desired behavior.
.Model(model => {
model.Id(Inspection => Inspection.DEPInspectionsID);
model.Field(Inspection => Inspection.CloseoutStatusID).DefaultValue(2);
model.Field(Inspection => Inspection.InspectionStatus).DefaultValue(1);
})

Related

Kendo MVC TreeList not Rendering from Initial BindTo

My MVC ViewModel contains the initial list of records to be displayed within my Kendo TreeList. However, the TreeList is NOT rendering the initial list...and I don't understand why.
REQUIREMENTS:
If initial records exist...display them
The READ ACTION CANNOT be executed on the initial render (other controls manage that later)
For other Kendo controls, you set:
AutoBind(false)
BindTo(Model.MyCollectiom)
...and the READ ACTION does not execute. But the TreeList is failing at the moment.
MY RAZOR LOOKS LIKE:
At initial render records DO EXIST (see image below)
#(Html.Kendo().TreeList<DeviceHierarchyDataItem>()
.Name("treeTarget")
.Columns(columns =>
{
columns.Add().Field(e => e.DisplayName)
.TemplateId("tmplDisplayName")
.Title(" ");
})
.BindTo(Model.TargetDevices)
.AutoBind(false)
.DataSource(dataSource => dataSource
.Read(read => read.Action("find", "devicehierarchy", new { Area = "" })
.Data("window.etp.pageController.getFilter"))
.ServerOperation(false)
.Model(m =>
{
m.Id(f => f.Id);
m.ParentId(f => f.ChildOf);
m.Expanded(true);
m.Field(f => f.DisplayName);
}))
.Sortable())
Strangely enough the TreeList MVC control doesn't support binding to local data...
At least not in july 2018...
The recommendation is to use the jquery control instead.
And then convert the data from the Model to a json string:
$(document).ready(function () {
var dataSource = new kendo.data.TreeListDataSource({
data: #Html.Raw(Json.Encode(#Model.TargetDevices)),
schema: {
model: {
id: "Id",
parentid: "ChildOf",
expanded: true
}
}
});
I hope it helps!

multiple data sources in kendo ui dropdownlistfor?

I using the following:
#(Html.Kendo().DropDownListFor(m => m.AbcID)
.OptionLabel("Select Abc")
.DataTextField("AbcName")
.DataValueField("AbcID")
.AutoBind(true)
.HtmlAttributes(new { style = "width: 300px" })
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("AutoCompleteAbcList", "Common").Data("GetSelectedXyz");
});
})
So basically what's happening is that the dropdownlist is being populated by the Json returned by the AutoCompleteAbcList ActionMethod.
What I'd like to know is that I have another ActionMethod ddlPQRList that returns a Json and I'd like to populate my dropdownlist using both the Jsons.
I have tried the following:
#(Html.Kendo().DropDownListFor(m => m.AbcID)
.OptionLabel("Select Abc")
.DataTextField("AbcName")
.DataValueField("AbcID")
.AutoBind(true)
.HtmlAttributes(new { style = "width: 300px" })
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("AutoCompleteAbcList", "Common").Data("GetSelectedXyz");
read.Action("ddlPQRList", "Common").Data("GetSelectedXyz");
});
})
but do not get the desired output. I get the list from the 2nd ActionMethod only.
Any help is appreciated. Thanks.
No, this is not possible the way you are trying to do it. A widget can only have one dataSource.
The second read Action is overwriting the first. It is the same thing as setting a variable value twice...only the second one counts.
If you want the dataSource of the DropDownList to be the concatenation of list, then you need to create a single controller action that returns that list, i.e.:
read.Action("AutoCompleteAbcListANDddlPQRList", "Common").Data("GetSelectedXyz");
where the implementation of AutoCompleteAbcListANDddlPQRList() returns a single list of BOTH AutoCompleteAbcList and ddlPQRList lists.

Multiselect list in Kendo Grid inline editing

I need to use multiselect list in kendo grid (inline editing) so that user can select multiple values from the list per row.
Following are my requirements:
At the time of display, kendo grid should show comma separated list of all the selected values.
At the time of Add, kendo grid should show multiselect list and allow to select multiple values.
At the time of Edit, kendo grid should show multiselect list with already selected values. User should be able to modify the select and add/remove items from the list.
When user clicks on update/save button, selected values from multiselect list should be available in code behind (in update ajax action) along with id of row.
Following what I do as of now:
I am taking an approach similar to using a drop down list in kendo inline grid.
I have created an Editor Template for displaying multiselect at the time of add/edit.
Following is the code:
#model List<Namespace.CompanyConnector>
#using Kendo.Mvc.UI
#(Html.Kendo().MultiSelectFor(c=>c)
.Name("company_connector_id")
.DataTextField("connector_name")
.DataValueField("company_connector_id")
.Placeholder("Select connector...")
.AutoBind(false)
.Value((List<int>)ViewData["SelectedValues"])
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCompanyConnectors", "BrandConnector");
})
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
Explanation: I bind a list of model class to the multiselect and set data source in the read action. For selecting the selected values at the time of edit, I have created a function that returns the ids of selected values and put that in View Data in the read action.
I've used this Editor template in my Index page as following code:
#{Html.Kendo().Grid<Cee.DomainObjects.DomainObjects.BrandConnector>()
.Name("BrandConnectorGrid")
.Filterable()
.Events(e => e.Edit("onEdit"))
.DataSource(dataSource => dataSource
.Ajax()
.Events(e => e.Error("error_handler").RequestEnd("onRequestEnd"))
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.brand_id);
model.Field(e => e.CompanyConnectorList).DefaultValue(new
List<Cee.DomainObjects.DomainObjects.CompanyConnector>());
})
.Read(read => read.Action("_AjaxBinding", "BrandConnector",new{companyID = 0 }).Type(HttpVerbs.Post))
.Update(update => update.Action("_UpdateBinding", "BrandConnector").Type(HttpVerbs.Post)))
.Columns(columns =>
{
columns.Bound(c => c.brand_connector_id).Width(0).Hidden(true);
columns.Bound(c => c.company_id).Width(0).Hidden(true);
columns.Bound(c => c.brand_id).Width(0).Hidden(true);
columns.Bound(u => u.brand_name).Title("Brand").Width("18%").HtmlAttributes(new { #class = "brkWord", #readonly = "readonly" });
columns.ForeignKey(u => u.connector_name, Model.CompanyConnectorList, "company_connector_id", "connector_name").Title("Connector").Width
("16%").HtmlAttributes(new { #class = "brkWord" }).EditorTemplateName("company_connector_id");
columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { #title = "Edit" })).Width("16%").Title("Edit");
})
.Editable(editable => editable.Mode(GridEditMode.InLine).CreateAt(GridInsertRowPosition.Top))
.Pageable(pageable => pageable.Refresh(true).PageSizes(GlobalCode.recordPerPageList).ButtonCount(GlobalCode.PageSize).Input(true).Numeric(true))
.HtmlAttributes(new { #class = "dynamicWidth" })
.Sortable(sorting => sorting.Enabled(true))
.Render();
}
Explanation: I've used ForeignKey. Bound it to the string column "connector_name". Connector_name is a comma separated list of IDs that I send from controller. Editor template is used here.
Issue: It works fine at the time of View/Display in Index but Edit does not show selected value. Also we do not get updated value in code behind on update click.
Is this correct way of implementing multiselect list or do I need to bind a collection property as a column in grid?
If I bind a collection property as a column then how would I be able to show comma separated string at the time of display?
Try below code:
function onEdit(e) {
var multiselect = $("#YourMutliselectDropdown").data("kendoMultiSelect");
var IDArray = [];
$(e.model.propertyName).each(function (index) {
var ID = e.model.propertyName[index].id;
IDArray.push(ID);
});
multiselect.value(IDArray);
}
I assume that propertyName is List of your collection and it contains id as property.
try it:
c.Bound(p => p.CompanyConnectorList).ClientTemplate("#= connectorsToString(data)#").EditorTemplateName("company_connector_id");
and js:
function connectorsToString(data) {
var list = data.company_connector_id;
var result = "";
for (var i = 0; i < list.length; i++) {
result += list[i].Name + ';';
}
return result;
}

How to format the row based on condition in kendo ui mvc grid

I am working on asp.net mvc. I am trying to display list of messages in a Kendo mvc ui grid.
I have written the code like,
Html.Kendo().Grid((List<messages>)ViewBag.Messages))
.Name("grdIndox")
.Sortable(m => m.Enabled(true).SortMode(GridSortMode.MultipleColumn))
.HtmlAttributes(new { style = "" })
.Columns(
col =>
{
col.Bound(o => o.RecNo).HtmlAttributes(new { style = "display:none" }).Title("").HeaderHtmlAttributes(new { style = "display:none" });
col.Bound(o => o.NoteDate).Title("Date").Format("{0:MMM d, yyyy}");
col.Bound(o => o.PatName).Title("Patient");
col.Bound(o => o.NoteType).Title("Type");
col.Bound(o => o.Subject);
}
)
.Pageable()
.Selectable(sel => sel.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.DataSource(
ds => ds.Ajax().ServerOperation(false).Model(m => m.Id(modelid => modelid.RecNo))
.PageSize(10)
//.Read(read => read.Action("Messages_Read", "Msg"))
)
.Events(ev => ev.Change("onSelectingGirdRow"))
)
and i have the field in the table like IsRead-boolean type. so if the message is unread message then i need to format that record with bold font. I have used clientTemplates but with that i am able to format only particular cells i want format entire row. Please guide me.
as Sanja suggested you can use the dataBound event but it will be better to cycle through the tr elements (the rows). Also I assume that you will need the related dataItem to check if the property that indicates if the message is read.
e.g.
dataBound: function ()
{
var grid = this;
grid.tbody.find('>tr').each(function(){
var dataItem = grid.dataItem(this);
if(!dataItem.IsMessageRead)
{
$(this).addClass('someBoldClass');
}
})
}
You can use dataBound event to change your rows.
dataBound: function ()
{
$('td').each(function(){
if(some condition...)
{
$(this).addClass('someBoldClass')}
}
})
}
There is another way to do that.It's called RowAction.
.RowAction(row =>
{
if (condition)
{
row.HtmlAttributes["class"] = "someBoldClass";
}
})
Please note that the RowAction is available only for rows that are rendered on server side. So in your case, you can use RowAction as an alternative to DataBound.

telerik datetime format in custom grid editor template is not correctly passed to controller

I have a custom editor template for a vehicle part that is used in a telerik grid for insertion in mvc3 razor. The editor template includes a datetime field. On insertion of a new vehicle part the datetime field is incorrect and the format is changed.
For example, if I insert "06/10/2011" which is day 6 , month 10 and year 2011 , in the controller, the dateTime field in the model is "10/06/2011" which is day 10 month 6 and year 211. I am using telerik's date picker
Basically the day and month are becoming switched after submitting to the controller
I have other instances in my code where I am passing a datetime field without an issue, so I believe the problem is the fact that I'm using a custom editor template ...
Here is the code for the grid:
#(Html.Telerik().Grid<VehiclePartsViewModel>()
.Name("VehiclePartsViewModel")
.ToolBar(commands =>
{ commands.Insert();
})
.DataKeys(keys => keys.Add(c => c.Id))
.ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
.DataBinding(dataBinding => dataBinding
.Ajax()
.Insert(MVC.Vehicles.CustomCoverage._InsertPart().GetRouteValueDictionary())
.Select(MVC.Vehicles.CustomCoverage._SelectPart().GetRouteValueDictionary())
.Update(MVC.Vehicles.CustomCoverage._SavePart().GetRouteValueDictionary())
.Delete(MVC.Vehicles.CustomCoverage._DeletePart().GetRouteValueDictionary())
)
.Columns(columns =>
{
omitted..
})
.Footer(false)
.Editable(editing => editing.Mode(GridEditMode.PopUp))
The simplified editor template is :
<div>
#Html.LabelFor(v => v.ItemId, new { #class = "uc-caption"})
#Html.EditorFor(v => v.ItemId)
</div><br />
<div>
#Html.LabelFor(v => v.InstallDate, new { #class = "uc-caption"})
#Html.EditorFor(v => v.InstallDate, new { Modifiable = true })
</div>
I am also using an editor template for dateTime, but I do not believe the issue is here:
#(
Html.Telerik().DatePicker()
.Name(ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty))
.HtmlAttributes(new { id = ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty) + "_wrapper" })
.ShowButton(true)
.Value(Model.HasValue ? Model.Value : new DateTime())
.ClientEvents(events => events.OnChange("onChangeDatePicker"))
.InputHtmlAttributes(new { style = "width:100%"})
.Enable(ViewData["Modifiable"] != null ? (bool)ViewData["Modifiable"] : true)
)
Thanks
Ok so I was finally able to resolve this with telerik .. there seems to be a problem with setting globalization to true .. You have to add a line before it .. This is what my _layout.cshtml looks like now ..
#(Html.Telerik().ScriptRegistrar()
.OnDocumentReady(#<text></text>) //Telerik: This is required because there is still no Telerik components on the page and jQuery(document).ready will not be rendered and the globalization will not work
.Globalization(true)
You probably have problems with globalization/localization of your app.
Different cultures are mixed up.
I had the same problem when posting float values, and solved it by adding this method to Global.asax.cs:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
}

Resources