How to change kendo grid column width after bound in mvc? - c#

I'm trying to set width for one of the columns kendo grid.
Here the simple code:
#(Html.Kendo()
.Grid<MyObject>()
.Name("Name")
.TableHtmlAttributes(new { style = "height: auto;" })
.Columns(c => {
c.Bound(m => m.ObjectId).Hidden();
c.Bound(m => m.Type).Title()
//Bound other fields
if (Model.Property)
{
c.Bound(m => m.Price).Title()
.HeaderHtmlAttributes(new {title = "Price"});
//Here I want to change the width of my first column
c.Container.Columns.Where(x => x.Title == "Type").FirstOrDefault.Width(200);
}
})
.Scrollable(src => src.Height(261))
.DataSource(ds => ds
.Ajax()
.Events(e => e.Error("app.ui.kendo.onGridError").RequestEnd("app.ui.project.onRequestEnd"))
.Read(r => r
.Action("Action", "Controller", new { Id = #Model.Id })
.Type(HttpVerbs.Get))))
The problem is that compiler said "Method, delegate or event expected". Are there another ways to change width after bounding the column?

To Change it after bound you have to
1) Attach an event in kendo grid like
#(Html.Kendo().Grid<SomeModel>()
.Name(Model)
.Events(e => e.DataBound("some_name"))
2) In Jquery
function some_name(e) {
// Access the column here to set the width
$('#SomeField').width(percentage)
}

This question has been answered before by Telerik themselves. Here ya go!
http://www.telerik.com/forums/change-column-widths-after-grid-created
It looks like it's unsupported out of the box, or was so in 2013 at least. Personally I would just grab the options from the grid, change the width of the column you need, and then re-apply these options to the grid.
My workplace uses Kendo for all our UI's and this is probably the easiest way I've found to edit multiple options after databound, even if they're not exposed through Kendo methods.
Code below is just an example, probably missed something but should get you started.
var grid = $("#Name").data("kendoGrid");
var opts = grid.options;
opts.columns[0].width = "1000px";
grid.setOptions(y);
I don't believe this requires a grid refresh, but it might. Also I believe you can use the string name of the field tied to the column instead of the index.

Related

Make all columns editable when adding a record while existing records only allow some columns to be edited

Problem Description
I am trying to implement a grid using Telerik UI that is used to display/update/create records. The grid is configured to use in-cell editing and for updating, only some of the columns are editable, but when the user adds a record, every cell of the newly added row should be editable. I have already tried to hook the Edit event and make the field editable, however by doing so, not only the Title cell of the new row becomes editable, but also the existing Title cells.
The relevant code sections of the view can be found below.
Data.cshtml
<script>
'use strict';
function onEdit(event) {
if (event.model.isNew()) {
event.model.fields.Title.editable = true;
}
}
</script>
#(Html.Kendo().Grid<DataViewModel>()
.Name("DataGrid")
.Columns(columns =>
{
columns.Bound(model => model.Title);
columns.Bound(model => model.Description);
columns.Bound(model => model.Count);
})
.Editable(edit => edit.Mode(GridEditMode.InCell))
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Events(events => events
.Edit("onEdit")
)
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Read("DataRead", "Data")
.Create("DataCreate", "Data")
.Update("DataUpdate", "Data")
.Model(model =>
{
model.Id(x => x.Id);
model.Field(x => x.Title).Editable(false);
})
)
)
Kendo UI v2020.2.617, Telerik.UI.for.AspNet.Core 2020.2.617
One option would be rather than setting the model editable property and hooking the onEdit event, you could try the following which will call a js function to determine if the column should be editable:
#(Html.Kendo().Grid<DataViewModel>()
.Name("DataGrid")
.Columns(columns =>
{
columns.Bound(model => model.Title).Editable("titleEditable");
columns.Bound(model => model.Description);
columns.Bound(model => model.Count);
})
//truncated for brevity
<script>
function titleEditable(dataItem) {
return dataItem.isNew();
}
</script>

Kendo MVC MultiSelect Not displaying selected values

When I am using a MutliSelect Kendo control, it is not populating the pre selected items. e.g. when it loads it is not loading the ones define in my model
Model.WheelsetExchanges[i].ReasonCodeIds
The kendo control looks like this
#(Html.Kendo().MultiSelectFor(x => Model.WheelsetExchanges[i].ReasonCodeIds)
.Placeholder("Select Reason Code...")
.DataTextField("Value")
.AutoClose(false)
.DataValueField("Id")
.HtmlAttributes(new { #class = "multiselect--clause" })
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetWerReasonCodes", "ReferenceData");
})
.ServerFiltering(true);
})
)
Any idea why the previous selected reason codes are not being displayed when I load the page?
It seems okay what you're doing on the view- but can you check whether you're getting data on the server side?

Dynamic Scrolling Telerik MVC Grid

I am trying to take off the pagination from a couple of Telerik MVC Grids that have a large amount of data loaded into them (upwards of 5000, probably more once they hit production). With our smaller grids, I would just take off the Pageable property(see code below) and the scrolling functionality just works.
With the larger grids I get a JSON error saying that the length of the string exceeds the value set on the maxJsonLength property. I updated the webconfig to be set to the max value as per this links suggestion but it still gave me the same error.
The version of Telerik that I am using is plain Telerik(not Kendo) and is the MVC version (main UI DLL is Telerik.Web.MVC, version 2012.2.801.340).
All documentation that I have found either points me to the new version of Kendo or a RadGrid, which is not included/supported in my version.
Is there a way to acheive this, either by loading it all at once like this does here, or creating a dynamically loading grid using the Telerik version I have, or am I out of luck? I am also open to suggestions for another way to achieve this, but the results have to be in a Grid of some sort.
Below is the basic code for what I have for all grids. The larger grids that I am having issues with have more columns than this one which help account for the JSON error.
#(Html.Telerik().Grid<ApportionmentCode>()
.DataBinding(dataBinding => dataBinding.Ajax().Select("AjaxGetAppCodes", "AppCode"))
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.Id)
.Title("ID")
.Width(50)
.HtmlAttributes(new { #class = "text-center" })
.Hidden();
columns.Bound(o => o.Code)
.Title("AppCode")
.Width(90)
.HtmlAttributes(new { #class = "text-center" });
columns.Bound(o => o.Description)
.Title("Description")
.HtmlAttributes(new { style = "min-width: 200px;" })
.ClientTemplate("<span class=\"clip tooltip\"><#= Description #></span>");
columns.Command(commands =>
{
commands.Custom("edit")
.Text("Edit")
.ButtonType(GridButtonType.Image)
.Action("Edit", "AppCode")
.ImageHtmlAttributes(new { #class = "t-edit", title = "Edit" })
.DataRouteValues(route => route.Add(o => o.Id));
})
.Width(78)
.HtmlAttributes(new { #class = "nowrap" })
.IncludeInContextMenu(false);
})
.ToolBar(commands => commands.Custom()
.Text("Add")
.Action("Create", "AppCode", Request.GetRouteValues())
.ButtonType(GridButtonType.ImageAndText)
.ImageHtmlAttributes(new { #class = "t-add" })
.HtmlAttributes(new { #class = "addButton" }))
.Filterable()
.ClientEvents(events =>
{
events.OnDataBound("onDataBound");
events.OnComplete("AddGridFilter");
events.OnLoad("OnGridLoad");
})
.ColumnContextMenu()
.Sortable()
.Pageable(paging => paging.PageSize(20).Style(GridPagerStyles.NextPreviousAndNumeric).Position(GridPagerPosition.Bottom)) //When removed, this is the line that causes the JSON error
.Resizable(resizing => resizing.Columns(true))
.Scrollable(a => a.Height("auto")))
Thanks in advance
In the controller, I assume you have something like:
DataSourceResult result = model.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
If you use the Newtonsoft package and change it to this, this should allow a larger amount of data through.
DataSourceResult result = model.ToDataSourceResult(request);
var json = Newtonsoft.Json.JsonConvert.SerializeObject(result);
return Content(json, "text/json");
EDIT:
If the problem is too much data and you don't want paging, how about trying virtualization by adding:
.Scrollable(scrollable => scrollable.Virtual(true))
You'll still need a page size, an example is here: http://demos.telerik.com/aspnet-mvc/grid/virtualization-remote-data

Partial View in kendo grid column

I have an ajax enabled kendo grid with a client template that displays data from the model to which the row is bound.
(because of ajax, using columns.Template seems not possible.)
#(Html.Kendo().Grid<Model>()
.Columns(columns =>
{
columns.Bound(x => x.SubModel).ClientTemplate("bla #= SomePropertyOfSubModel # bla")
})
.DataSource(dataSource => dataSource.Ajax())
This works basically, but I am not satisfied with the result. For ex., I have problems to make kendo controls in the template work. I would rather hang a partial view in the client template, but did not succeed. The farthest I got was
columns.Bound(x => x.SubModel).ClientTemplate(Html.PartialView("view", //??) //how to bind to SubModel?
.ToHtmlString())
Any help is appreciated.
I think you need .ToClientTemplate() in your kendo control template,
view.cshtml
#(Html.Kendo().NumericTextBox()
.Name("NameHere")
.Min(0)
.HtmlAttributes(new { style = "width:200px" })
.ToClientTemplate()
)
And then,
columns.Bound(c => c.SubModel).ClientTemplate(Html.Partial("view").ToHtmlString());
Edit:
If you want to bind a model to the partial view, you could do
columns.Bound(c => c.SubModel.Property).Template(#<text>Html.Partial("view", item.SubModel)</text>);
Here's another way to accomplish this.
#(Html.PageElement().Kendo().Grid<myModel>()
.Name("GridName")
.Columns(col =>
Html.RenderPartial("Partials/_myDamnedPartial", col)

Rebind grid with combobox, how to get selected value?

I work with Telerik-MVC and I'm trying to rebind a grid when I change the value of a combobox. Everything seems working except I can't get selected value of my combobox.
Here is my code :
Grid :
#{Html.Telerik().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.Col1);
columns.Bound(o => o.Col2);
columns.Bound(o => o.Col3);
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("_MyAction", "MyController")
)
.ClientEvents(events => events.OnDataBinding("Grid_onDataBinding"))
}
Combobox :
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.HtmlAttributes(new { id = "ComboBoxCode" })
.BindTo(new SelectList(Model.GroupBy(x => x.Code)
.Select(o => o.First()).ToList(),
"Code", "Code"))
.ClientEvents(events => events
.OnChange("onComboBoxChange")
)
)
Script :
function onComboBoxChange(e) {
$("#Grid").data("tGrid").rebind();
}
function Grid_onDataBinding(e) {
var code = /* I need to get the combobox value here */;
e.data = { myCode: code };
}
Controller :
[GridAction]
public ActionResult _MyAction(string myCode)
{
Console.WriteLine("Code : " + code);
/*
Set new model here
*/
return View(new GridModel(newModel));
}
I tried things like :
var e = document.getElementById("ComboBoxCode");
var code = e.options[e.selectedIndex].text;
But it doesn't work. Can you tell me how to fix this problem and get the right value ?
The problem is that when you rebind the grid, you didn't really use the ComboBox selected value. Your onComboBoxChange function tells the grid to rebind, which it does by going to the _MyAction method. At no point did you pass in the ComboBox value. What you should do is before databinding, grab the selected value and pass it to your controller action. See http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-grid-client-api-and-events.html#OnDataBinding for details. Something like this:
function Grid_onDataBinding(e) {
var combobox = $('#ComboBox').data('tComboBox');
e.data = { code: combobox.value };
}
(Note that I actually haven't done any work with the ComboBox, so this isn't tested, but this should at least get you on the right path. See ComboBox documentation.)

Categories

Resources