Selecting all options in kendo multiselect - asp.net-mvc

I have in my application a Kendo Multiselect component where I select my available options.
my View is like this:
div class="editor-field col-width45">
<div>
#(Html.Kendo().MultiSelectFor(model => model.FeaturesValues)
.DataTextField("Name")
.HtmlAttributes(new { #class = "size100Percent", Id = "FeaturesSelect" })
.DataValueField("Id")
.Placeholder("Selecione...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetFeatures", "Role");
})
.ServerFiltering(false);
}))
</div>
</div>
I want to select all the options at once, and not be selecting one by one.
I looked for a way to do this and all the solutions brought me to this result:
I added a button in my View.
I created a Js function to select all:
my code stayed like this:
div class="editor-field col-width45">
<div>
#(Html.Kendo().MultiSelectFor(model => model.FeaturesValues)
.DataTextField("Name")
.HtmlAttributes(new { #class = "size100Percent", Id = "FeaturesSelect" })
.DataValueField("Id")
.Placeholder("Selecione...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetFeatures", "Role");
})
.ServerFiltering(false);
}))
</div>
</br>
<div>
#(Html.Kendo().Button()
.Name("SelectAll")
.HtmlAttributes(new { type = "button" })
.Content("Selecionar todos")
.Events(ev => ev.Click("selectAll")))
</div>
JavaScript:
function selectAll() {
var multiSelect = $("#FeaturesSelect").data("kendoMultiSelect");
var selectedValues = [];
for (var i = 0; i < multiSelect.dataSource.data().length; i++) {
var item = multiSelect.dataSource.data()[i];
selectedValues.push(item.Id);
}
multiSelect.value(selectedValues);
multiSelect.trigger("change");
}
my result is this:
multiselect with button add all
Everything is working perfectly !!!
My question is:
Is it possible to create a checkbox inside the kendo Multiselect, to be used as select all, and not have this button?
What I want is something like this:
[multiselect without button][2]
enter image description here

You can add checkbox to header template which can be used to select - de select all elements.
Check this demo dojo
Though example here is shown using a Kendo UI JS, you can accomplish it using Kendo ASP.NET as well.
#(Html.Kendo().MultiSelect()
....
.HeaderTemplate("<label><input type='checkbox' id='selectAll'> Select All</label>")

I have prepared a quick dojo for you here. https://dojo.telerik.com/UpAFIdEx
This should hopefully be what you are after. I have just applied some simple styling just to get things looking a bit like your second image. but if you are using bootstrap or have css that handles positioning of elements this should work for you.
Any issues/questions let me know.

Related

Telerik Grid: Handle click event on thick button within custom template opened on edit command

I am using a Telerik grid in an ASP.NET MVC view. I am completely new in Telerik.
My Telerik grid is as below:
#(Html.Telerik().Grid<MyDTOs.DetalleDTO>()
.Name("GridActividadesOferta")
.DataKeys(keys =>
{
keys.Add(d => d.indiceInterno).RouteKey("indiceInterno");
})
.Columns(columns =>
{
columns.Bound(cl => cl.nombreActividad).Title(Inspecciones.lblGridActividad.ToUpper()).ReadOnly(true).HtmlAttributes(new { #class = "actividad-column" });
columns.Bound(cl => cl.nombreSubActividad).Title(Inspecciones.lblGridSubActividad.ToUpper()).ReadOnly(true);
columns.Bound(cl => cl.articuloId).Title(Inspecciones.lblGridArticulo.ToUpper()).ReadOnly(true);
columns.Bound(cl => cl.CCAA_Expediente).Title("Expediente".ToUpper()).ReadOnly(false).Width(100);
columns.Bound(cl => cl.CCAA_Instalacion).Title("InstalaciĆ³n".ToUpper()).ReadOnly(false).Width(100);
columns.Bound(cl => cl.importeArticulo).Title("Importe".ToUpper()).ReadOnly(false).Width(100).Format("{0:c}").ClientFooterTemplate("<#= $.telerik.formatString('Total factura') #>");
columns.Bound(cl => cl.importeTasa).Title(Resources.Inspecciones.lblGridImporteTasa.ToUpper()).ReadOnly(false).Aggregate(aggr => aggr.Sum().Count())
.Width(100)
.Format("{0:c}")
//.ClientFooterTemplate("<#= $.telerik.formatString('{0:c}'," + Model.totalFactura + ")#>")
.ClientFooterTemplate("<#= '<span id=spanTotalFactura>' + $.telerik.formatString('{0:c}'," + Model.totalFactura + ") + '</span>' #>")
.Width(100)
.Format("{0:c}");
columns.Command(commands =>
{
commands.Edit().ButtonType(GridButtonType.Image);
commands.Delete().ButtonType(GridButtonType.Image);
}).Width(100).Visible(!ViewBag.readOnly);
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("SelectGridVacias1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
.Update("UpdateGridActividadesRegularizables1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
.Delete("DeleteGridActividadesRegularizables1", "Expedientes", new { ofertaComercialId = #Model.ofertaComercialId })
;
})
.ClientEvents(events => events.OnDataBinding("onDataBindingArticulosGrid").OnDataBound("onDataBoundWrapper").OnEdit("onEditDatosArticulo")
.OnRowDataBound("onRowDataBound").OnDelete("onDelete").OnError("onErrorGrid"))
.HtmlAttributes(new { #class = "center-columns" })
.Selectable()
.Editable(editing =>
{
editing
.Mode(GridEditMode.PopUp)
.TemplateName("DatosArticuloTemplate1")
.InsertRowPosition(GridInsertRowPosition.Top);
})
)
As you can see above, I have two commands defined, Edit and Delete. The edit command button has a custom template specified in ".Editable". This template is called "DatosArticuloTemplate1" and it is as follows:
<div style="width:800px">
<div class="row-fluid">
<div class="span12">
#Html.Label("nombreArticulo", "Descripcion actual".ToUpper())
#Html.TextAreaFor(m => m.nombreArticuloFacturacion, new { style = string.Format("width:{0}px; ", 800) })
#Html.ValidationMessage("instalacionId")
</div>
</div>
<div class="row-fluid">
<div class="span2">
#Html.Label("importeArticulo", "Importe".ToUpper())
#(Html.Telerik().NumericTextBoxFor(model => model.importeArticulo).EmptyMessage("Importe").DecimalDigits(2).InputHtmlAttributes(new { style = "width:90px;" }))
</div>
<div class="span3">
#Html.Label("importeTasa", "Importe de tasa".ToUpper())
#(Html.Telerik().NumericTextBoxFor(model => model.importeTasa).EmptyMessage("Importe").DecimalDigits(2).InputHtmlAttributes(new { style = "width:90px;" }).Value(0))
</div>
<div class="span7">
#Html.Label("unidades", "InstalaciĆ³n".ToUpper())
#{Html.RenderAction("DropDownListInstalaciones", "SeleccionarInstalacionButton",
new
{
area = "",
clienteId = Model.OfertaComercial == null ? "" : Model.OfertaComercial.clienteId,
actividadId = Model.actividadId,
subActividadId = Model.subActividadId,
sociedadId = Model.OfertaComercial == null ? "" : Model.OfertaComercial.sociedadId,
dataBindTo = "instalacionId"
});
}
</div>
</div>
</div>
This custom template looks like this:
As you can see at the bottom left corner of the custom template, there are two buttons, one to validate the values introduced (thick button) and another to cancel. These buttons are from Telerik.
Now, I am trying to handle the click event on the thick button. Within the click event i want to validate the value introduced for "IMPORTE" field. If value introduced for this field is 0 then I want to popup a javascript alert modal window. This alert window must notify to the user that a value greater than 0 must be entered for that field. Also, custom template window "DatosArticuloTemplate1" must not be closed until user types in a correct value (value > 0) in the "IMPORTE" field. So how can I do it?

How to Change label value on drp selected change event in MVC

I have below code and I want to change label text base on selected role.
For example, If I select Admin then in label Text I need "Admin Name" etc.
I use below code but I is not working.
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleID, new SelectList(ViewBag.RoleLsit, "Id", "RoleName"), "Select Category", new { onchange = "SelectedIndexChanged()" })
</div>
<div>
#Html.LabelFor(model => model.RoleName)
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<script type="text/javascript">
function SelectedIndexChanged() {
var sub = document.getElementsByName("RoleName");
sub.value = "Selected Role Name";
}
Thanks
You could find your elements using #Html.IdFor, if your js is in your view.
function SelectedIndexChanged() {
//find the label
var label = document.querySelector('label[for="#Html.IdFor(m => m.RoleName)"]');
//get the dropDown selected option text
var dropDown = document.getElementById("#Html.IdFor(m => m.RoleId)");
var selectedText = dropDown.options[dropDown.selectedIndex].text;
//set the label text
label.innerHTML=selectedText
}
By the way, taking a look a jQuery might be an "interesting" option.
You could simply remove the new { onchange = "SelectedIndexChanged()" , then
$('##Html.IdFor(m => m.RoleId)').change(function() {
$('label[for="#Html.IdFor(m => m.RoleName)"]').text($(this).children('option:selected').text());
});
function SelectedIndexChanged() {
document.getElementsById("RoleName").InnerHtml="Role name goes here";
}
you should use get element by id instead of name because when this html helper renders the strongly typed binded attributes becomes the id of that control . so in your case role name will be the ID

Kendo Window - LoadDataFrom finds argument value inline?

I have a kendo window which I want to populate depending on a selection made in a dropdown. I've tried refreshing the window upon open, but I can't figure out how to make that work. Changing gears, I'm wondering if I can instead send a variable parameter to the controller within window declaration itself, and then do a simple window.refresh (instead of coding the refresh to hit a specific controller, which isn't working).
I mean something like this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = $("#ContactId").data("kendoComboBox").value() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Or this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = getContact() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Obviously neither of these work, but I'm wondering if there's another way to fill in this field?
Thank you!
edit: Adding relevant code from controller and window/partial view. My controller is now being hit, but my window is not pulling the correct data. Any ideas?
Window:
#model [taking out company info].Contact
#using Kendo.Mvc.Extensions
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset id="infoForm">Hello, world.
#Html.HiddenFor(model => model.ContactId, new { id = "EditWindowId" })
<br />
<label id ="ContactNameID" style="width: 130px;">Contact Name</label>
<span>
#Html.TextBoxFor(model => model.FullName, new { type = "text", id = "EditWindowName", #class = "k-textbox form-control", style = "width: 200px; cursor:default" })
</span><br />
</fieldset>
}
Controller:
[HttpGet]
public ActionResult _ContactEdit(int selectedContact)
{
var entities = from r in dbContext.Contacts
where r.ContactId == selectedContact
select r;
if (entities.Any())
{ return PartialView(entities.First()); }
else
{ return HttpNotFound("Contact does not exist."); }
}
You can leverage the change event of your dropdown list to grab the selected value. Once you have the selected value you can programmatically refresh the window with the appropriate action on your controller. For example, the code below defines a Kendo DropDownList with a subscription to the change event. In the change, the value is used to build a dynamic url, and the kendo window is refreshed with that url:
<%= Html.Kendo().DropDownList()
.Name("dropdownlist")
...
.Events(e =>
{
e.Change("onChange")
})
%>
<script type='text/javascript'>
function onChange(){
var value = this.value(),
window = $("#EditWindow").data("kendoWindow");
window.refresh({
url: "/Contact/_ContactEdit?selectedContact=" + value
});
}
</script>

Fire validation of asp.net razor view page input controls on kendo ui upload select file button

I have an asp.net mvc application with Kendo UI controls. I have an upload file razor view with few input controls on the page.
My requirement is to fire the page validation on the file select button for all the other input controls in the page. (at least required validation has to get fired)
I can have a submit button and fire the validation. But I need to have that functionality on the Kendo UI upload select button. i.e,User can select / browse file to upload only after filling valid values for all the input controls.
I have done many searches and trial and error methods in my code but nothing helped.
I am new to Kendo UI controls so please help
Thanks in advance,
I am attaching sample code below:
#{
ViewBag.Title = "Kendo Validate";
}
#model KendoInputs_Validation.Models.ViewModel
#using(Html.BeginForm())
{
<div id="tickets">
<h3>Book Tickets</h3>
<ul id="innerList">
<li>
#Html.LabelFor(m => m.ComboBox)
#Html.Kendo().ComboBoxFor(m => m.ComboBox)
#Html.ValidationMessageFor(m => m.ComboBox)
</li>
<li>
#Html.LabelFor(m => m.DropDownList)
#(Html.Kendo().DropDownListFor(m => m.DropDownList)
.OptionLabel("Select item...")
.BindTo(new SelectList(new string[] { "Item1", "Item2", "Item3" }))
)
#Html.ValidationMessageFor(m => m.DropDownList)
</li>
<li>
#Html.LabelFor(m => m.DatePicker)
#Html.Kendo().DatePickerFor(m => m.DatePicker)
#Html.ValidationMessageFor(m => m.DatePicker)
</li>
<li>
#Html.LabelFor(m => m.Number)
#Html.Kendo().NumericTextBoxFor(m => m.Number)
#Html.ValidationMessageFor(m => m.Number)
</li>
<li class="accept">
<button class="k-button" type="submit">Submit</button>
</li>
<li>
#(Html.Kendo().Upload()
.Name("files")
.Messages(msg => msg
.Select("Browse")
))
</li>
</ul>
</div>
}
<script>
$(document).ready(function () {
/* Bind Mutation Events */
var elements = $("#tickets").find("[data-role=combobox],[data-role=dropdownlist],[data-role=numerictextbox],[data-role^=date], [data-role^=upload]");
//correct mutation event detection
var hasMutationEvents = ("MutationEvent" in window),
MutationObserver = window.WebKitMutationObserver || window.MutationObserver;
if (MutationObserver) {
var observer = new MutationObserver(function (mutations) {
var idx = 0,
mutation,
length = mutations.length;
for (; idx < length; idx++) {
mutation = mutations[idx];
if (mutation.attributeName === "class") {
updateCssOnPropertyChange(mutation);
}
}
}),
config = { attributes: true, childList: false, characterData: false };
elements.each(function () {
observer.observe(this, config);
});
} else if (hasMutationEvents) {
elements.bind("DOMAttrModified", updateCssOnPropertyChange);
} else {
elements.each(function () {
this.attachEvent("onpropertychange", updateCssOnPropertyChange);
});
}
});
function updateCssOnPropertyChange (e) {
var element = $(e.target);
element.siblings("span.k-dropdown-wrap")
.add(element.parent("span.k-numeric-wrap"))
.add(element.parent("span.k-picker-wrap"))
.toggleClass("k-invalid", element.hasClass("input-validation-error"));
}
</script>
<style type="text/css">
.k-widget > span.k-invalid,
input.k-invalid
{
background: red;
}
#innerList li
{
margin: 10px 10px;
}
</style>
Edit:- I can write an Select event for the upload control as below:
#(Html.Kendo().Upload()
.Name("files")
.Events(events => events
.Select("onSelect")
)
)
But in this case user has to select a file for getting the validation errors.
Our requirement is that when user clicks the select button validation errors should pop up. if no errors then only file select window opens.
Thanks
You can bind a click function to your upload during initialization and check your custom vale before the default behavior, the browse fro dialog, window is invoked.
$(document).ready(function () {
$("#yourUploadName").click(function (e) {
var valid=myValidationFunction();
if (!valid) {
alert("Bad");
//This will cancel the showing of the search dialog
e.preventDefault();
}
});
});

allow blank selection with kendoDropDownList

I want to add a blank selection item for KendoUi dropdownlist. I followed the same as mentioned in the below link.
http://www.kendoui.com/forums/ui/dropdownlist/how-to-allow-blank-selection-with-kendodropdownlist.aspx
But if I call the below in document.ready event,
$("#ddl").data("kendoDropDownList").one("open", function() {
$(this.ul[0].firstChild).html(" ");
});
I get error 'one' is null or undefined error. I have added the required reference files. What might be causing this? Is there any other way to add blank selection option?
I have defined the combobox as below in my mvc view.
<span class="list">
#(Html.Kendo().DropDownList()
.Name("facility").Events(events => events.Change("facilityChange"))
.OptionLabel(" ")
.DataSource(source => source.Read(read => read.Action("_GetFacilitiesForComboBox", "SuccessionInfo")))
.DataTextField("FacilityName")
.DataValueField("FacilityId")
.Value(Model.NextJobFacilityId.ToString())
.HtmlAttributes(new { style = "width:300px" })
)
</span>
Please help.
Achieved it by adding css
.k-popup .k-list .k-item {
min-height: 1.8em;
}
Reference - http://www.kendoui.com/forums/ui/dropdownlist/empty-selectitems-do-no-display-correctly.aspx

Resources