I have the following Kendo DropdownList:
@(Html.Kendo().DropDownListFor(m => Model.CmtsId).Name("#=uid#CmtsId")
.Animation(false)
.DataSource(a => a.Read(r => r.Url("/webAPIpath")))
.DataTextField("Text")
.DataValueField("Value")
.OptionLabel("Select")
.ToClientTemplate())
The following code is at the other end of "webAPIpath" and builds a SelectList for the above dropdown to use as a list of options:
var results = await _cmtsService.GetAllCmts(LogData);
if (results.Status == ResponseStatus.Success)
{
var markets = await _locationService.GetMarketsForHeadEndAsync(headEnd, LogData);
var prevSelected = await _pendingChangesService.GetPendingPortSelections(nodeId, LogData);
var list = new List<SelectListItem>();
foreach (var cmts in results.Data.Where(a => markets.Data.Any(b => b.Id == a.MarketId)))
{
var market = markets.Data.FirstOrDefault(a => a.Id == cmts.MarketId);
var mfg = _deviceService.GetManufacturerAsync(cmts.ManufacturerId, LogData);
var model = _deviceService.GetModelAsync(cmts.ModelId, LogData);
await Task.WhenAll(mfg, model);
list.Add(new SelectListItem()
{
Text =
$"cmts{cmts.Number}-{market.MarketAbbreviation} / {mfg.Result.Data.Manufacturer} / {model.Result.Data.Model} / {cmts.DocsisCapability}",
Value = cmts.Id.ToString()
});
}
//Set selected value if previous selection exists
foreach (var item in list.Where(item => item.Value.Equals(prevSelected.Data?.NewCMTSID.ToString())))
{
item.Selected = true;
}
return Ok(list);
}
return InternalServerError(results.Exception);
What I want is for the item
in list
which has item.Selected = true;
to be the default value of my dropdownlist. I can't for the life of me figure out how to get the kendo dropdown to respect the Selected status of the item in th selectlist it binds to. All the kendo documentation I have found tells me to either use .Value()
or .SelectedIndex()
but I can't do this (or don't know how I would) because the 'Selected' item in the list is determined dynamically from a separate database query, so I would have to make a separate call and then do a compare and set the value via javascript/jquery.
So in a nutshell, how do I get Kendo().DropDownListFor to set the default selected option to be the item in my SelectList with Selected = true;
If you are binding to a primitive value (it appears you are), you need to add an attribute (note the underscores, not dashes):
@(Html.Kendo().DropDownListFor(m => Model.CmtsId).Name("#=uid#CmtsId")
.Animation(false)
.DataSource(a => a.Read(r => r.Url("/webAPIpath")))
.DataTextField("Text")
.DataValueField("Value")
.OptionLabel("Select")
.HtmlAttributes(new { data_value_primitive = "true" })
.ToClientTemplate())