How does the Kendo UI cascading DropdownList works? - asp.net-mvc

Can Anyone explain to me the structures of this codes?
For an instance .Name("products") is the DropDownList name, I would like to know for what are those (what do you call this (Name, OptionLabel, etc.)) because it really confuse me. I'm stuck in creating a cascading DropDownList.
#(Html.Kendo().DropDownList()
.Name("products")
.OptionLabel("Select product...")
.DataTextField("ProductName")
.DataValueField("ProductID")
.DataSource(source => {
source.Read(read =>
{
read.Action("Type", "ComboBox")
.Data("filterProducts");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("categories")
)
<script>
function filterProducts() {
return {
categories: $("#categories").val()
};
}
</script>
<p>
<label for="orders">Orders:</label>
#(Html.Kendo().DropDownList()
.Name("orders")
.OptionLabel("Select order...")
.DataTextField("ShipCity")
.DataValueField("OrderID")
.DataSource(source => {
source.Read(read =>
{
read.Action("SubType", "ComboBox")
.Data("filterOrders");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("products")
)
<script>
function filterOrders() {
return {
products: $("#filterOrders").val()
};
}
</script>

.Name("orders"): This is the unique name to assign to the dropdown html element.
.OptionLabel("Select order..."): This is what the dropdown should display when no option is selected.
.DataTextField("ShipCity"): This is the property of the datasource that populates the dropdown options that should be displayed in the dropdown.
.DataValueField("OrderID"): This is the property of the bound datasource that populates the dropdown options that should be used as the value to bind to the underlying model of the view.
read.Action("SubType", "ComboBox"): This defines the Action and Controller that should be called to retrieve the collection that will populate the dropdown options
.Data("filterOrders"): this is used to assign parameters to the above read.Action method
.ServerFiltering(true):
.Enable(false): Whether or not the dropdown is enabled.
.AutoBind(false): Whether or not the dropdown should immediately bind to its dropdown datasource (or wait for the cascade from dropdown to be assigned a value)
.CascadeFrom("products"): The other DropDownList to cascade from. If AutoBind is false, then this dropdown will only bind to its options datasource once the other dropdown has been assigned a value by the user.

Related

Selecting all options in kendo multiselect

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.

Using Kendo UI MVC DropDownListFor, how do i pass the selected text along to the controller during the submit form?

Im using Ajax.BeginForm and I need to pass the selected text to the controller on the submit. Right now it is passing the Value(id) but I need the Text. Any ideas?
#using (Ajax.BeginFrom("Index", "Home", new AjaxOptions { HttpMethod = "Post" }))
{
<fieldset>
<ol>
<li>
#(Html.Kendo().DropDownListFor(m => m.Office)
.Name("officeDropDownList")
.DataValueField("Value")
.DataTextField("Text")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetOffices", "Home");
});
})
)
</li>
</ol>
</fieldset>
}
To get the value text of a dropdown:
$("#ddl").data("kendoDropDownList").text();
**Edit**
In order to return this data to the Controller I believe you need to change the .Name of the ddl to match the ViewModel property. So in your case change to .Name("Office").

MVC | Kendo Grid | Pass the data from View to the controller

I am using a kendoui Grid which is populated with some data. The grid has one Template column, of check-box and some other columns with Client Template that includes a Text-box in it.
I need to now pass the data of the rows, that are selected using a check-box, to the controller action.
The updated values in the text-box should be passed to the controller.
Let me know if anyone has the solution for the same.
This is the Grid
#(Html.Kendo().Grid<MMM.Lumos.Entities.CustomEntities.TestPlanTestPointMappingViewModel>()
.Name("ATPGrid")
.Columns(columns =>
{
columns.Bound(p => p.IsSelected).ClientTemplate("<input type='checkbox' value='#= IsSelected #' " + "# if (IsSelected) { #" + "checked='checked'" + "# } #" + "/>").Width(40);
columns.Bound(p => p.TestPointName).Filterable(false).Width(60);
columns.Bound(p => p.PassThreshold).ClientTemplate(Html.Kendo().IntegerTextBox().Name("mp_#=TestPointId#").Min(0).HtmlAttributes(new { value = "#=PassThreshold#", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
columns.Bound(p => p.FailThreshold).ClientTemplate(Html.Kendo().IntegerTextBox().Name("mp_#=TestPointId#").Min(0).HtmlAttributes(new { value = "#=FailThreshold#", style = "width: 50px;" }).ToClientTemplate().ToHtmlString()).Width(60);
})
.Scrollable()
//.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("ATPGrid_Read", "TestPlan"))
)
)
I have a submit button
<input type="submit" name="Add" formmethod="post" onclick="PostData()" value="Add" />
Javascript function
<script>
function PostData() {
var griddata = $("#ATPGrid").data("kendoGrid");
alert(JSON.stringify({ griditems: griddata.dataSource.view() }));
//$.ajax(
// {
// type: 'POST',
// url: '/configuration/testplan/Add',
// dataType: 'json',
// contentType: "application/json; charset=utf-8",
// data: JSON.stringify({ griditems: griddata.dataSource.view() }),
// success: function (result) {
// alert('success');
// }
// });
}
</script>
I need to get the values of this grid on click of add button. As you can see i have a Client Template Columns, Check-box and Text-box in the grid.
I need to get the values from this text-box and pass it to the controller.
It would be great if only those which are selected using check-box should be passed to the controller.
I am not sure whether there is simple way of passing values from View to Controller in Kendo UI Grid. But i have followed the below way in third party MVC Grid to pass the checkbox values. You can bind this function to button click event. It could be too long for simple operation. May be it could be useful for you which you can optimize for your needs.
function PostData(sender, args) {
        var tempCheckedRecords = new Array();
        var gridobj = $find("Grid1"); // getting Grid object. Modify it for KendoUI grid.
        if (sender.checked == true) {
            ... //retrieve the records here
            tempCheckedRecords.push(records[0]); // pass the selected records in the array
        }
        var tempRecords = new Array();
        $.each(tempCheckedRecords, function (index, element) {
            var record = {};
            record["Column0"] = element.IsSelected; // column names in Grid
            record["Column1"] = element.TestPointName; // you can get the text box values in the element.
            record["Column2"] = element.PassThreshold;
            tempRecords.push(record);
        });
        var params = {};
        var visibleColumns = gridobj.get_VisibleColumnName();
        $.each(tempRecords, function (i, record) {
            $.each(visibleColumns, function (j, value) {
                params["Test[" + i + "]." + this] = record[value];
            });
        });
        $.ajax({
            type: 'post',
            url: "/configuration/testplan/Add",
            datatype: 'json',
            data: params,
            success: function (data) {
                return data;
            }
        });
    }
Explore adding an AJAX update call in your Kendo Grid:
.Datasource(datasource => datasource.Ajax
.Read(read => read.Action(...))
.Update(update => update.Update("UpdateAction", "Controller))
Then in your controller add an Action:
public ActionResult UpdateAction(IEnumerable<NewsModel> model)
{
//...do stuff
}

How to Validate `Kendo ComboBox` in ASP.NET MVC

I have Kendo ComboBox useing it in MVC Project.
#(Html.Kendo().ComboBox()
.Name("ddl")
.DataTextField("cName")
.DataValueField("iID")
.HtmlAttributes(new { style = "font-size:95%;" })
.AutoBind(true)
.Animation(false)
.Filter(FilterType.StartsWith)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("MethodName", "ControllerName");
});
})
)
But I want validation for this ComboBox on Button Click if no value is selected in ComboBox then button click not occur.
Do anyone have any ideas for validating this ComboBox?
I am assuming your button is supposed to submit value you have selected in the ComboBox.
1) store your combobox in a variable combobox (optional)
2) validate in following way
$("#submitbutton").click(function() {
if (combobox.value() != '') {
// submit here
}
});

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