How to change configuration option in Kendo UI ASP.Net MVC - asp.net-mvc

We're using Kendo UI via MVC wrappers.
Here's how we create a MultiSelect:
#(Html.Kendo().MultiSelect()
.Name("filterUsers")
.DataTextField("Text")
.DataValueField("Value")
.Placeholder("Select users...")...
The problem is that in new version of Kendo UI there's an option clearButton which has no wrapper in MVC.
How can we set it while continue using MVC wrappers? I tried:
1) Data attributes (data-clear-button), but it doesn't work since it requires all settings to be defined via attributes and the widget to be created via kendo.Bind
2) Altering configuration via setOptions, which doesn't work:
$(function() {
var s = $("#multiselect").data('kendoMultiSelect');
s.setOptions({clearButton: false});
});
Any suggestions?

The suggestion of DontVoteMeDown can work for specific MultiSelects, but needs a modification:
$("#multiselect").data("kendoMultiSelect").wrapper
.find(".k-multiselect-wrap > .k-i-close").css("display", "none");
Otherwise the previously suggested implementation will also hide the close buttons for any pre-selected items.
If you want to target all MultiSelects, then use one of the following instead:
CSS
.k-multiselect-wrap > .k-i-close {
visibility: hidden;
}
or
JavaScript
// execute this before any MultiSelects are initialized
kendo.ui.MultiSelect.fn.options.clearButton = false;

Related

Kendo validator not working on text change

I am using kendo controls for my project. I was using jquery validation to validate my controls at client side but as jquery validation is not working for kendo controls so I am using kendo validators to validate the controls.
I am using dataannotation validation with MVC 5 project. Here is sample dojo.
It is working perfect but the validation only appear on focus-out or blur event. Is there any way to validate control on change of value of control like jquery validation?
Update:
Here is the complete solution that helped me to resolve this issue:
if ($.validator !== undefined) {
$.validator.setDefaults({
ignore: [],
highlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap") ||
element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else if (element.parent().children('.k-upload-empty').length > 0) {
highLightElement = $(element.parent().children('.k-upload-empty')[0]);
} else {
highLightElement = element;
}
highLightElement.addClass('input-validation-error');
},
unhighlight: function (element, errorClass) {
element = $(element);
var highLightElement;
if (element.parent().hasClass("k-picker-wrap")
|| element.parent().hasClass("k-numeric-wrap")) {
highLightElement = element.parent().parent();
}
else if (element.parent().hasClass("k-widget")) {
highLightElement = element.parent();
} else {
highLightElement = element;
}
highLightElement.removeClass('input-validation-error');
}
});
}
You have 2 ways to meat your purpose:
Using jQuery Unobtrusive Validation with KendoUI
Background
As you know the Kendo UI Editor creates a different elements than HTML form elements. Other JavaScript editors work in a similar fashion. The actual HTML is hidden using CSS (display: none;), and therein lies the issue. By default jQuery Validation ignores hidden input fields. There are validation data-* attributes on the form elements, but since it is hidden, when the unobtrusive validation fires, the editor is ignored.
Solution
You have 2 ways to solve this issue and perfectly work with both technologies. Read the Making the Kendo UI Editor Work With jQuery Validations and if you have any problem for implementing, please read Kendo UI NumericTextBox With jQuery Validation as an example for NumericTextBox
Then, You may have problem to assign proper CSS class in case of validation. You can read adding jquery validation to kendo ui elements.
Just using KendoUI Validators
You should implement desired event for the validation purpose. Here you need onChange event to work like jQuery Unobtrusive Validation. Use the following code as it describes what to do:
$(document).ready(function () {
function widgetChange() {
//place validation logic
};
$("#dropdownlist").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
change: widgetChange
});
})
You may want to use both of them! So take a look at .Net Mvc 3 Trigger (other than submit button) Unobtrusive Validation
Update
A dojo for implementing with last solution which added a pattern="\d+" to search input with a validation message. The validation is called by filtering event for the same input. Note that you should use desired event based on UI element, here we used filtering for autocomplete instead of using change for DropDownList.
I recently found a new implementation which is looking good to try and test. That is available at aspnet-mvc getting-started validation

How to bind a Kendo MultiSelect helper via external event

I have a MVC Kendo MultiSelect helper that I want to set up but NOT retrieve the data for until an external event if fired. Im using it in a cascading capacity with a drop down list and don't what to show any values to select until the dropDownList has a selected value. Everything is working fine except this one annoyance.
#(Html.Kendo().MultiSelect()
.Name("productMultiSelect")
.DataTextField("Name")
.DataValueField("Id")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetProducts", "OrderProductAdmin3");
});
})
I tried setting the AutoBind property to false but the MultiSelect helper still did and initial DataBind.
I think I can use code like this to data bind it when the external event is fired
var productMultiSelect = $("#productMultiSelect").data("kendoMultiSelect");
if (!DataBound) {
productMultiSelect.dataBind();
DataBound = true;
}
Thank you for your help.
Earl
I'm just going to show and hide it as appropriate.

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

Controling height in jQuery UI Accordion with dynamic data

I'm using an jQuery accordion control with knockout to dynamically add/remove items to the control based on some client-side activity. I've created a knockout binding like such:
ko.bindingHandlers.accordion = {
init: function (element, valueAccessor) {
var options = valueAccessor() || {};
setTimeout(function () {
$(element).accordion(options);
}, 0);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).accordion("destroy");
});
},
update: function (element, valueAccessor) {
var options = valueAccessor() || {};
$(element).accordion("destroy").accordion(options);
}
}
Now my problem is the sizing of the accordion... it always looks very compressed (vertically). I've tried setting the height of the DIV that contains the control, like this:
<div id="LearningPaths" data-bind="foreach: allLearningPaths, accordion: {}" style="height:500px; border:1px solid red;">
But the panels in the accordion don't change... they still aren't very "tall". Here's what it looks like: http://sdrv.ms/STA9Y6
I think there's a setting I can pass in when I use the .accordion(), but with my binding handler I'm not sure how to do that as I'm already passing in the 'options' object.
What I want is to have the content area of each panel to expand to the entire available side in the accordion control... ideas?
First i think your problem is someone related to SharePoint web parts. I created a accordion solution which is based on the summary link web part in SharePoint and can be found here: http://www.n8d.at/blog/turn-summary-link-web-part-into-an-accordion/
I wrote my own accordion to accomplish this, which also makes sure that if you like to edit the page the accordion script won't be loaded.
On the other hand i think your problem is more related to css and not to jquery. Do you use float style in your css? Then you need to make sure that you use the so called clear-fix.
This can be done in define the following style:
.panel:after{
clear: both;
}

SetFoucsOnError in mVC

I am trying to set focus on the control while error occurs. I am use mvc 2.0. In Asp.net we have a property SetFoucsOnError but in MVC what is the substitute of it and how to implement ?
Well I did not get this solution. But i got an alternate option which even works :
$().ready(function() {
$("#Form").submit(function() {
$('.input-validation-error').focus();
$(".input-validation-error").each(function() {
$(this).focus();
});
});
});
I think the easiest way to do this is to use JavaScript.
The example uses jQuery and assumes controls with invalid data have a css class called input-validation-error:
$(function () {
$('form').submit(function() {
$(this).find('input.input-validation-error, select.input-validation-error')
.first()
.focus();
});
});
This will look for all input and select elements with the class input-validation-error, take the first of them and put the focus on it.

Resources