Kendo UI DropDownListFor Set SelectedValue - kendo-ui

I'm working with Kendo UI on an MVC application. We have a grid and when the user opens the row for editing we have a dropDownList that holds company names. I'm trying to get the DDL to default to the company name that's pertinent to the row.
Here's the column code:
columns.Bound(e => e.company_business_name).Width(220).Title("Company")
.EditorTemplateName("CompanyName");
and here's the editorTemplate code:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.BindTo((System.Collections.IEnumerable)ViewData["Companies"])
)
and the method that fills the DDL:
private void PopulateCompanies()
{
var companyList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(Session["Companies"] as string))
{
companyList = (List<SelectListItem>)Session["Companies"];
}
else
{
companyList = new DataAccess().GetCompanies(CurrentSettings.getUser().userId);
CacheCompanies(companyList);
}
ViewData["Companies"] = companyList;
}
EDIT:
Updated the code. The DDL still populates but I'm still not getting the selected value when I click "edit" on the grid row. Feel like I'm close here, help!

The problem is that your Editor Template's model is your entire model, not the company_business_name property (Very bad name for a property, by the way. You need to follow the standard naming conventions).
You don't even need to fill the drop down list.
Your Editor Template should be something like this:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(x =>
x.Read(read => read.Action("GetCompanies", "AddEntry"))
)
)

Related

Kendo ui mvc dropdownlistfor with boolean type value using Entity Framework

#Html.Kendo().DropDownListFor(model => model.Is_Active)
//instead of #Html.EditorFor(model => model.Is_Active)"
I am using entity crud operation and Is_Active is a boolean type value. On generating edit view it shows dropdown list which code is
#Html.EditorFor(model => model.Is_Active)
and I want to change it in kendo ui using
#Html.Kendo().DropDownListFor(model => model.Is_Active)
but it shows blank dropdown list - please provide a response
You need to specify the DataSource for the DropDownList otherwise there is no list of items in it. You use the .BindTo() for that.
Html.EditorFor() works because the internal implementation for a boolean creates the True/False item list for you.
When you explicitly define a DropDownList you need to provide both the value AND the list of potential values using .BindTo(), i.e.
#{
var boolDataSource = new List<SelectListItem>()
{
new SelectListItem() { Text = "True", Value = "True" },
new SelectListItem() { Text = "False", Value = "False" }
};
// Or however/wherever you want to define the list of items that the DropDownList uses.
}
#Html.Kendo().DropDownListFor(model => model.Is_Active).BindTo(boolDataSource)

how to get selected value for Kendo DropDownList

I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:
#model KendoApp.Models.SelectorViewModel
The ViewModel is defined as:
public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
and in My view I have:
#(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?
For anyone who found this wondering how to get the selected value in JavaScript, this is the correct answer:
$("#EncounterTypes").data("kendoDropDownList").value();
From the documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-value
when select a value from a dropdown list, and in the selec event , we can get the selected value as following ,
#(Html.Kendo().DropDownList()
.Name("booksDropDown")
.HtmlAttributes(new { style = "width:37%" })
.DataTextField("BookName")
.DataValueField("BookId")
.Events(x => x.Select("onSelectBookValue"))
.DataSource(datasource => datasource.Read(action => action.Action("ReadBookDropDow", "PlanningBook").Type(HttpVerbs.Get)))
.OptionLabel("Select"))
javascript function like following ,
function onSelectBookValue(e) {
var dataItem = this.dataItem(e.item.index());
var bookId = dataItem.BookId;
//other user code
}
I believe this will help someone
Thanks
Hello I was just going through this problem,kept on searching for 2 hours and came up with a solution of my own.
So here is the line to fetch any data bidden to the kendo drop down.
$("#customers").data("kendoDropDownList").dataSource._data[$("#customers").data("kendoDropDownList").selectedIndex].colour;
Just change the id customers to the id you have given tot he kendo drop down.
Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:
#(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.
BUT should you need to use the hidden field for some reason, put it there, subscribe the the select event of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.
It's your choice :)
If you want to read also out the text of the dropdown, you can get or set the value by using the following kendo function:
$('#EncounterTypes').data("kendoDropDownList").text();
REFERENCE TO THE DOCUMENTATION
Using this .val() as #Vivek Parekh mentions will not work - there is no function .val() in the kendo framework.
If you want you could use jQuery and get the value back: $('#EncounterTypes').val()
Updated DEMO
$("#EncounterTypes").kendoDropDownList().val();
You can get the selected item like following code and then use item.property to get further information
var selectedFooType = $("#fooType").data("kendoDropDownList").dataItem();
selectedFooType.name
//OR
selectedFooType.id

Kendo UI ASP.Net MVC ForeignKey column DataSource in InCell Edit mode

I have Kendo Grid and a ForeignKey column on a page. ForeignKey column is populated using ViewData as described below.
column.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName");
The Grid is editable in batch(InCell) mode as show below...
.Editable(editable => editable.Mode(GridEditMode.InCell)
I want to modify collection of ProductID column in the grid after page is loaded based on value selected on other drop-down defined outside of the Grid.
How can I achieve that? Can I do it using jQuery?
Similar example I found here...
http://www.telerik.com/community/forums/aspnet-mvc/grid/cascading-dropdowns-in-grid-edit---foreignkey-columns.aspx
Thanks.
I figured out how to filter the Product drop-down using an EditorTemplate for the foreign key column.
Here is my column definition for the Product.
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName").EditorTemplateName("ProductIDEditor");
Here is the editor template for Product, ProductIDEditor.cshtml
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.OptionLabel("Select a value...")
.DataTextField("ProdName")
.DataValueField("ID")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("FilterProducts", "Home").Data("filterProducts"))
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
In my main VIEW Index.cshtml, I added filterProducts JavaScript handler, that passes JSON object for productID to controller.
function filterChargeTypes()
{
return {
productID: $("#ProductID").val()
};
}
Here is the controller that listens to filtering event...
public ActionResult FilterProducts(string productID)
{
// do your filtereing based on productID.
}
FilterProducts will be called every time when user hits the drop-down to get filtered value.
You don't need the Editor Template. It will bind to a dropdown without it. You can use this, like you had, just minus the template:
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName")
or
c.ForeignKey(x => x.ProductID, (System.Collections.IEnumerable)ViewData["products"], dataFieldValue: "ID", dataFieldText: "ProdName")
And for filtering, you can just invoke .Filterable() on the grid.

Loop through IEnumerable in #Html.DropDownListFor (MVC3)

I have a collection of models that I am passing to my view and I want to display each model.property in the dropdownlist. The problem is there is a bug in my code where it shows two duplicate items.
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#Html.Label("BRAD Module:")&nbsp
#Html.DropDownListFor(model => model.FirstOrDefault().module_name, Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name }), new { id = "ddlSelectedBrad", onchange = "chkSelection()" })
I am currently using FirstOrDefault() to access the module name for each model in my collection of models. But by doing this I have a duplicate value.
See screenshots below:
MARKET:LEISURE is showing twice
Intelligence is showing twice. If I change this dropdown value and return to this screen it will show two duplicate values.
Summary
Does anyone know a better way of writing the LINQ query?
Thanks.
Instead of
Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name })
Try
Model.GroupBy(x => x.module_name).Select(x => new SelectListItem { Text = x.First().module_name, Value = x.First().module_name })
This should filter the duplicate records.

Telerik MVC3 Razor Grid - Partial View returning from Controller

I have a view with several controls that are used for searching. When a user searches (Ajax.BeginForm) off of these I return the data into a PartialView (Telerik MVC3 Grid) that was generated dynamically.
This all works fine. In the grid are buttons for selecting a row. When I select a row, it posts to my controller, I do some "stuff" etc. When I try to get back to the view all I get is my grid data on a page by itself, it displays like a table with no borders, no other controls etc. My code is below.
My partial grid:
#model Highlander.Areas.Highlander.Models.ViewModels.DeliveriesGridViewModel
#using System.Data;
#(Html.Telerik().Grid<System.Data.DataRow>(Model.Data.Rows.Cast<System.Data.DataRow>())
.Name("Grid")
.DataKeys(dataKeys => dataKeys.Add("DeliveryID"))
.Columns(columns =>
{
columns.Command(commandbutton =>
{
commandbutton.Select().ButtonType(GridButtonType.ImageAndText);
}).Width(80).Title(ViewBag.Title);
columns.LoadSettings(Model.Columns as IEnumerable<GridColumnSettings>);
})
.DataBinding(dataBinding => dataBinding.Server().Select("_MarkSystem", "Deliveries"))
.EnableCustomBinding(true)
.Resizable(resize => resize.Columns(true))
)
My Controller:
[GridAction]
public ActionResult _MarkSystem(GridCommand command, int id)
{
string shipDeliver = DataCache.ShipDeliver;
DataTable fullTable = DataCache.FullTable;
// call to function to get the datatable data based on the id
rHelpers.GetDataTableRow(id, fullTable, shipDeliver);
// get the data for the grid into the model
fullTable = DataCache.FullTable;
model = new DeliveriesGridViewModel();
model.Data = fullTable;
model.Columns = rHelpers.NewColumns(DataCache.FullTable);
return PartialView("_DeliveryGrid", model);
//if (Request.IsAjaxRequest())
//{
// return PartialView("_DeliveryGrid", model);
//}
//return PartialView("_DeliveryGrid", model);
//return PartialView("DeliveryManager", model);
}
As you can see I have tried various things with no success.
Can anyone give me some direction on this.
Thanks for your time.
As far i understand you are using dataBinding.Server() that call a server side binding. Use .Editable(editing => editing.Mode(GridEditMode.InLine) it will work.
Both kind of bindings (Server and Ajax) needs a editing mode. Put an editing mode and try again.Kindly Response if it does not work for you. Here full code of data binding:
**.DataBinding(dataBinding => dataBinding.Ajax()
.Select("myAction", "myController")
.Update("myAction",myController")).
Editable(editing => editing.Mode(GridEditMode.InLine))**

Resources