Kendo UI Grid in MVC with Conditional Custom Command Button - asp.net-mvc

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.

Related

How to change configuration option in Kendo UI 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;

Radio button selection event in MVC

I am a beginer ...I don't know how to write code during the radio button select change in MVC....I have used it like this
In csHTML page
#Html.RadioButtonFor(model=>Sales.Pay_Mode, true)Cheque
#Html.RadioButtonFor(model=>Sales.Pay_Mode, false)Cas
This is my cs page code....Where i want write the change event code and how i get the selected value in control page.My requirement is during radio button change i want change the style of the textbox enable as false..
#Html.TextBox("ChequeNo")
Considering the information that you have provided in your question, the following code would fulfill your expectation
#Html.RadioButtonFor(model => model.PayMode, "Cheque") Cheque
#Html.RadioButtonFor(model => model.PayMode, "Cas") Cas
#Html.TextBox("ChequeNo", null, new {id="theTextBox"})
<script type="text/javascript">
$("input[name='PayMode']").change(function () {
var selectedRadio = $("input[name='PayMode']:checked").val();
if (selectedRadio == 'Cas') {
$("#theTextBox").attr("disabled", "disabled");
} else {
$("#theTextBox").removeAttr("disabled");
}
});
</script>
The is no control events handler in MVC like in WebForms or something like this. You must use javascript code to implement your logic. For example with jQuery
$('.your-radio-class').change(function(){
$('#your-textbox-id').css('margin-left', '100px')
});

Using sortable with Tag-it jqueryui

I've been using the tag-it plugin from https://github.com/aehlke/tag-it (demo - http://aehlke.github.com/tag-it/examples.html).
In this code there is an option to display the inputted tags in another input, textarea etc. First option -
$('#singleFieldTags').tagit({
availableTags: sampleTags,
singleField: true,
singleFieldNode: $('#mySingleField')
});
Here the id - #singleFieldTags is the inputting field which is a list like <ul and id - #mySingleField displays the 'list-ordered' tags with commas between each.
All the tags that are added and removed in the #singleFieldTags appear in the #mySingleField. Since there is no built-it sortable function with tag-it, adding a sortable() to change the order of tags in #singleFieldTags, does not change the order of tags in #mySingleField.
The second option is a plain with only #singleFieldTags as follows :-
$('#singleFieldTags').tagit({
availableTags: sampleTags,
});
Although in tag-it.js there is a , the value does not appear in the mysql table after submitting the php form as the above list of tags is placed between <li></li>.
How is it possible to make the tags sortable and ensure that the same arrangement of tags in the list field <ul to be displayed in the <textarea as in First Option? Or How can the second option of sorting tags within a single field <input work and enabling it to be submitted by a form?
EDIT: There is a similar plugin like Tag-it called tagit here: http://webspirited.com/tagit/ . This plugin has sortable with an input box meaning if the tags were interchanged, and when submitted on form it would appear in the order of the sort. However, the disadvantage being that it has custom themeroller themes these are not similar and cannot even be linked to the ones at jQuery UI (jqueryui.com).
But on the other hand, the tag-it plugin (not tagit), can be loaded with these themes but does not provide the sortable function.
Here's a solution that uses the tag-it plugin, because I understand that your missing functionality is explained in your quote "...adding a sortable() to change the order of tags in #singleFieldTags, does not change the order of tags in #mySingleField".
In order to have "#mySingleField" reflect the new sort order, I'm adding a handler to the stop event of sortable():
$('#singleFieldTags').sortable({
stop: function(event,ui) {
$('#mySingleField').val(
$(".tagit-label",$(this))
.clone()
.text(function(index,text){ return (index == 0) ? text : "," + text; })
.text()
);
}
});
and
$('#singleFieldTags2').siblings(".tagit").sortable({
stop: function(event,ui) {
$('#singleFieldTags2').val(
$(".tagit-label",$(this))
.clone()
.text(function(index,text){ return (index == 0) ? text : "," + text; })
.text()
);
console.log( $('#singleFieldTags2').val() ); // just for reference
}
});
Here is a jsfiddle that demonstrates the functionality
(added functionality for single input field)

Chosen not working in jquery dialog on reloading mvc partial

I am loading two MVC Partial Views in jQuery UI dialog using following code for editing and adding a record:
$.get(url, function(data)
{
dialogDiv.html(data);
var $form = $(formid);
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse(document);
var dat = $form.data("unobtrusiveValidation");
var opts = dat ? dat.options || '' : '';
$form.validate(opts);
//THIS FUNCTION ADDS PLUGINS ETC.
runEditCreateStartScripts();
dialogDiv.dialog('open');
});
Following is the function that wires-up chosen functionality.
function runEditCreateStartScripts(){
$("select.chzn-select").chosen(
{
no_results_text: "no match",
allow_single_deselect: true
});
}
Everything is perfect on first call. After opening one dialog say edit a few times everything is broken. There is only hyperlink available in place of chosen stuff. This also happens if I open one dialog say add and then second dialog. The bindings and other functionality from first one (add) is gone.
Any insights on why this might be happening?
The problem that caused my issue was that the modals I was loading via AJAX had inputs with the SAME ID as an input field that was already on the page (using Django that has generic ID generators for model fields). This caused collision between the two inputs when re-triggering .chosen() on the selector. When I made the ID fields unique, all worked as expected.
Hope this would have helped.

DevExpress DateEdit using MVC

I have just started using the
<% Html.DevExpress().DateEdit()
control and i got it to work fine in my ASP.Net MVC application. The code is as shown below:
aspx page:
<% Html.DevExpress().DateEdit(settings =>
{
settings.Name = "EndDate";
settings.Properties.NullText = "dd/MM/yyyy";
settings.Properties.EditFormat = EditFormat.Custom;
settings.Properties.EditFormatString = "dd/MM/yyyy";
settings.Properties.DisplayFormatString = "dd/MM/yyyy";
settings.Date = Model.EndDate;
settings.Width = 100;
}
).Render();
%>
Above this code i have a reference to my javascript file (DateChanges.js) in this file i want to be able to do something like:
$(document).ready(function(){
$("#EndDate").change(function(){
//do whatever i want
});
})
I cant do this now cause using firefox i can see that the actual textbox that this datepicker assigns a value to has be named "EndDate_I". So my question is how can i easily do this since i want to be able to catch the change event of this control and play around with it in jQuery??
The DevExpress MVC Extensions offer their own infrastructure for the client-side processing needs (see the http://help.devexpress.com/#AspNet/CustomDocument6908 help topic to getting started).
It is necessary to handle the client-side ASPxClientDateEdit.DateChanged event, and retrieve the newly selected Date via the client-side ASPxClientDateEdit.GetDate() method. Use the retrieved js Date object for your additional needs:
<script type="text/javascript">
function OnDateChanged(s, e) {
var newDate = s.GetDate();
alert(newDate);
}
</script>
settings.Properties.ClientSideEvents.DateChanged = "OnDateChanged";
There is a rather long Blog post at http://kennytordeur.blogspot.com/2011/05/aspnet-mvc-where-is-clientid_10.html discussing your problem
( I think it is to long to have it pasted here, and the author deserves the credits )
following on from your comment on Mikhails's answer, there will be a property in the global namespace with the name of your control, so it's just like this:
CalculateDayDifference(s.GetDate(), EndDate.GetDate());
All the mvc controls do this, for some you might have to set the EnableClientSideApi property to start using them.

Resources