I use to my page of Kendo grid that have multi columns.
I want set a column width to autofit and change width automatically.
Plz help me , thanks
#(Html.Kendo().Grid<GardeshKar.Models.v_marhaleh_marahel>()
.Name("grdMarahel_Gardeshkar")
.ToolBar(toolbar => toolbar.Custom().Name("btnAddMarhaleh").Text("اضافه").HtmlAttributes(new { id = "btnAddMarhaleh", href = "#" }))
.Columns(columns =>
{
columns.Bound(c => c.Code).Width(50).Title("کد");
columns.Bound(c => c.Desc).Width(150).Title("شرح");//Autofit
columns.Command(c => c.Destroy().Text("حذف")).Width(70).Title("عملیات");
})
.HtmlAttributes(new { style = "height: 380px;" })
.Scrollable()
.Sortable()
.Resizable(rl => rl.Columns(true))
.Selectable(sl => sl.Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.DataSource(dataSource => dataSource
.Ajax()
.Model(m => m.Id(p => p.id))
.Read(read => read.Action("Get_DS_Marahel_Gardeshkar", "Home",
new { intGardesh = ViewBag.CodeGardeshKar }))
.Destroy(del => del.Action("Del_Marhaleh_GardeshKar", "Home")))
)
that column specific with autofit must column width change to autofit
One way is to remove the "Scrollable" property or you can use this function in dataBound event.
function Autocolumnwidth(e) {
var grid = e.sender;
for (var i = 0; i < grid.columns.length; i++) {
grid.autoFitColumn(i);
}
}
Related
I have the initial values for the grid in my ViewModel. But if the user wants to update values, I want to update my database, then send back the updated values for the grid from the backend. The problem is that the Ajax Read is always called. But it shouldn't because the (initial) values are there in the ViewModel and bound to Grid.
I tried setting the AutoBind to false, but it does not work, I get an error. (Cannot set AutoBind if widget is populated during initialization)
#(Html.Kendo().Grid<MyClass>()
.Name("MyClassGrid")
.BindTo(Model.MyClassList)
.Columns(column =>
{
column.Bound(c => c.SomeProp).Title("Some Property");
})
.Scrollable()
.DataSource(ds => ds
.Ajax()
.Read(read => read.Action("GetMyData", "CheckBar", new { param1 = Model.ParamFirst}))))
I want to display the already stored values for my grid, and only use the read operation if I want to update the values in my database too.
#(Html.Kendo().Grid<SQDCDashboard.Core.ViewModels.SafetyIncidentViewModel>()
.Name("safetyincident-grid")
.Columns(columns =>
{
columns.Bound(c => c.CreatedAt).HtmlAttributes(new { style = "width: 22%" }).Format("{0:MM/dd/yyyy}");
columns.Bound(c => c.Type).HtmlAttributes(new { style = "width: 22%" });
columns.Bound(c => c.Description).HtmlAttributes(new { style = "width: 22%" });
columns.ForeignKey(c => c.ProductionLineId, (System.Collections.IEnumerable)ViewData["ProductionLines"], "Id", "Name").HtmlAttributes(new { style = "width: 22%" });
columns.Command(command => { command.Edit(); }).HtmlAttributes(new { style = "width: 12%" });
})
.ToolBar(toolbar => toolbar.Create().Text("New Safety Incident"))
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(ds =>
ds.Ajax()
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.ProductionLineId).DefaultValue(Model.DefaultProdLine);
})
.Read(read => read.Action("GetSafetyIncidentList", "Safety"))
.Update(update => update.Action("EditSafetyIncidentInLine", "Safety"))
.Create(create => create.Action("CreateNewSafetyIncident", "Safety"))
)
.HtmlAttributes(new { style = "height: 100%" })
.Sortable()
.Filterable()
.Pageable()
.Mobile()
)
Here is an example of my grid. The Update(update => update.Action("Action" , "Controller"))
is the method you are wondering about. For my code I did not have to pass a parameter in with my read, and I do not need to pass one in with my Update.
[HttpPost]
public ActionResult EditSafetyIncidentInLine([DataSourceRequest] DataSourceRequest request, SafetyIncidentViewModel sivm)
{
if (sivm != null && ModelState.IsValid)
{
SafetyIncident si = _safetyIncidentService.Find(sivm.Id);
si.Description = sivm.Description;
si.ProductionLineId = sivm.ProductionLineId;
si.ProdLine = _productionLineService.Find(sivm.ProductionLineId);
si.Type = sivm.Type;
_safetyIncidentService.Update(si);
sivm.Id = si.Id;
sivm.CreatedAt = si.CreatedAt;
}
return this.Json(new[] { sivm }.ToDataSourceResult(request, ModelState));
}
This method is the one that is called when the Update button is pressed. The update button is created with the columns.Command(command => { command.Edit(); }; and the Editable(editable => editable.Mode(GridEditMode.InLine)). If you want more clarification or if your question is different let me know. I never got an error with having my grid already initialized when I was updating values.
I have a sample like this popup editing mode
I want to store my model while first inserting, and set default values.
#(Html.Kendo().Grid<License>()
.Name("popupGrid")
.Columns(columns =>
{
columns.Bound(p => p.LicenseId).Width(20).Hidden().HeaderHtmlAttributes(new { #title = "License" });
columns.ForeignKey(p => p.CustomerId, (System.Collections.IEnumerable)ViewData["customers"], "CustomerID", "CustomerName")
.Title("Customer").Width(200);
columns.Bound(p => p.VendorId).Width(20).HeaderHtmlAttributes(new { #title = "Vendor" });
columns.Bound(p => p.ProductId).Width(20).HeaderHtmlAttributes(new { #title = "Product" });
columns.Command(p => p.Edit().Text("Edit").HtmlAttributes(new { #title = "Edit" })).Width(80);
})
.ToolBar(toolbar => toolbar.Create().HtmlAttributes(new {#id ="MyAddButton" ,#title = "Add" }))
.Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("PopupEditView"))
.Events(e => e.Edit("onGridEdit").Save("onGridSave"))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.LicenseId))
.Create(create => create.Action("Create", "Home").Type(HttpVerbs.Post))
.Read(read => read.Action("Read", "Home").Type(HttpVerbs.Post))
.Update(update => update.Action("Update", "Home").Type(HttpVerbs.Post))
)
)
<script>
var myModel;
function onGridSave(e) {
if (e.model.isNew()) {
myModel = e.model;
}
}
function onGridEdit(e) {
if (e.model.isNew()&&myModel!=null) {
e.model.set("CustomerId", myModel.CustomerId);
e.model.set("VendorId", myModel.VendorId);
e.model.set("ProductId", myModel.ProductId);
}
}
</script>
But it's not working.
following code is not working too :
$(e.container).find('input[name="CustomerId"]').data("kendoDropDownList").value(myModel.CustomerId);//it's not giving error. but CustomerId is null in model of create method
Actually I want to this. But I don't know how to update datasource while prevent closing window.
You might try configuring your dropdownlist with valuePrimitive: true
http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#configuration-valuePrimitive
Im trying to use incell editing and use of the http://demos.telerik.com/aspnet-mvc/grid/editing-custom but is can't find my partial view that the dropdownlist should be rendered from.
Partial view (Testview.cshtml)
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownList()
.Name("ResourceType") // Name of the widget should be the same as the name of the property
.DataValueField("Id") // The value of the dropdown is taken from the EmployeeID property
.DataTextField("Name") // The text of the items is taken from the EmployeeName property
.BindTo((System.Collections.IEnumerable)ViewData["defaultResourceType"]) // A list of all employees which is populated in the controller
)
This is my grid:
#(Html.Kendo().Grid<RMS.Admin.ViewModel>()
.Name("ResourceGrid")
.Columns(columns =>
{
columns.Bound(c => c.ResourceId).Hidden();
columns.Bound(c => c.ResourceName);
columns.Bound(c => c.Descritption);
columns.Bound(c => c.ResourceType.Name).ClientTemplate("#=ResourceType.Name#");
columns.Bound(c => c.Approved);
columns.Bound(c => c.IsEnabled);
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(172).Title("Edit/Delete");
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(s => s.ResourceId);
model.Field(s => s.ResourceType).DefaultValue(ViewData["defaultResourceType"] as RMS.Admin.ViewModel.ResourceTypeId);
})
.Create(update => update.Action("CreateResource", "Home"))
.Read(read => read.Action("ReadResource", "Home"))
.Update(update => update.Action("SaveSystem", "Home"))
.Destroy(destroy => destroy.Action("RemoveSystem", "Home"))
)
)
Here is a part of my model:
public string ResourceUserId { get; set; }
[UIHint("Testview")]
public ResourceTypeId ResourceType { get; set; }
This is in my controller where i bind the data:
private void GetResourceTypeId()
{
//string [] list = new string[]{"Image", "Document", "Other"};
IList<ViewModel.ResourceTypeId> list = new List<ViewModel.ResourceTypeId>();
var a = new ViewModel.ResourceTypeId
{
Name = "Image",
Id = 1
};
var b = new ViewModel.ResourceTypeId
{
Name = "Document",
Id = 2
};
var c = new ViewModel.ResourceTypeId
{
Name = "Other",
Id = 3
};
list.Add(a);
list.Add(b);
list.Add(c);
ViewData["defaultResourceType"] = list.First();
}
I get this error when trying to render the grid:
The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
What am i missing?
First off your trying to bind just to one item with ViewData["defaultResourceType"] = list.First();. Instead you should bind to your whole list and then set the default option with .Value("1") so that it has "Images" by default.
#(Html.Kendo().DropDownList()
.Name("ResourceType")
.DataValueField("Id")
.DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["ResourceTypeList"])
.Value(ViewData["DefaultResourceType"])
);
Also for a template for a column in MVC you may just want to set it with EditorTemplateName
columns.Bound(e => e.myColumn).EditorTemplateName("dropdownTemplate")
And then define the template that you want to use somewhere else on the page.
<script id="dropdownTemplate" type="text/x-kendo-template">
#(Html.Kendo().DropDownList()
.Name("myDropDown")
.....
.ToClientTemplate()
)
</script>
If you would like you can also declare it as a stand alone template in your /Views/Shared/ folder. You would not have to add the .ToClientTemplate() or the script tags. You would reference it by the file name. You could then use the template on multiple pages in the project.
I have such Grid
#(Html.Kendo().Grid(Model.Differences)
.Name("formDifferencesList")
.HtmlAttributes(new { #class = "fullScreen" })
.Columns(columns =>
{
columns.Bound(e => e.Property);
columns.Bound(e => e.FieldPath);
columns.Bound(e => e.FieldType);
columns.Bound(e => e.Type);
columns.Bound(e => e.LeftValue);
columns.Bound(e => e.RightValue);
})
.Pageable()
.Sortable()
.Scrollable()
.Selectable()
.Resizable(resize =>
resize.Columns(true))
.Groupable()
.Filterable()
.DataSource(dataSource =>
dataSource.Ajax()
.PageSize(25)
.ServerOperation(false)
.Model(model => model.Id(e => string.Format("{0}{1}", e.Property, e.FieldPath)))))
RightValue and LeftValue is instance of type Object, it can be primitive value (like int, string), but also it can be a collection. If it is a collection I want to use Kendo ListView to represent it. How should I do that?
I tried to bound to the DataBound event
.Events(events => events.DataBound("onDifferencesDataBounded"))
added ClientTemplate to the Grid
columns.Bound(e => e.LeftValue).ClientTemplate("<div class='leftValueView'></div>");
and then inside js function tried to apply the template
<script type="text/javascript">
function onDifferencesDataBounded() {
$.each($('.leftValueView'), function () {
var grid = $('#formDifferencesList').data().kendoGrid;
var row = $(this).closest('tr');
var dataItem = grid.dataItem(row);
$(this).kendoListView({
dataSource: { data: dataItem },
template: kendo.template($("#leftValueTemplate").html())
});
});
}
</script>
<script type="text/x-kendo-template" id="leftValueTemplate">
// Not sure what should I do here?
</script>
Is there anything at all in the dataItem.LeftValue or RightValue such as Array, when you put a breakpoint there?
var dataItem = grid.dataItem(row); // <-breakpoint when you pass that line
If there is array such as number array [1,3,4,5] then you can give a try to use #=data# inside of the template.
I have such grid defined
#(Html.Kendo().Grid<FieldViewModel>(Model.Fields)
.HtmlAttributes(new { #class = "fullScreen" })
.Name("formFields")
.ClientDetailTemplateId("formFieldsTemplate")
.Columns(columns =>
{
columns.Bound(e => e.Key);
columns.Bound(e => e.DisplayName);
columns.Bound(e => e.FieldTypeName);
columns.Bound(e => e.Order);
columns.Bound(e => e.IsMandatory);
columns.Bound(e => e.Type);
})
.Pageable()
.Sortable()
.Scrollable()
.Selectable()
.Resizable(resize => resize.Columns(true))
.Groupable()
.Filterable()
.DataSource(dataSource => dataSource.Ajax().ServerOperation(false).Model(model => model.Id(e => e.Key))))
and details template
<script id="formFieldsTemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<FieldViewModel>()
.Name("FormField_#=Key#")
.ClientDetailTemplateId("formFieldsTemplate")
.Columns(columns =>
{
columns.Bound(e => e.Key);
columns.Bound(e => e.DisplayName);
columns.Bound(e => e.FieldTypeName);
columns.Bound(e => e.Order);
columns.Bound(e => e.IsMandatory);
columns.Bound(e => e.Type);
})
.DataSource(dataSource => dataSource.Ajax().Read(read => read.Action("LoadFieldDetails", "Forms", new { formPath = Model.Schema, rootElementName = Model.Root ,fieldKey = "#=Key#" })))
.Pageable()
.Sortable()
.Selectable()
.ToClientTemplate())
</script>
As you can see I have Type property (of type int), so what I want to do is not to show any details view and no arrow on the entire row when Type property is set to the specific value. How can I achieve it?
When you define your template like this, then it's used on client side. It's rendered by the #(Html.Kendo().Grid<FieldViewModel>() command but actually then used on client side. But you cannot compare a Type on clientside. but for example, when constructing the model you do:
if (myType is MyDataType) // Do the type check
{
myRow.UseTemplate = 1; // Define ID for template
}
else // ...and so on, can do a 'switch` or whatever
{
myRow.UseTemplate = 2;
}
And here is your template where you switch by Template ID:
<script id="formFieldsTemplate" type="text/kendo-tmpl">
# if (UseTemplate == 1) { #
<div>Template 1</div>
# } else { #
<div>Template 2</div>
# } #
</script>
Not sure if it will work properly if you have different data to display within your data rows... Hope you get the idea though.