Reputation: 4412
I have a Kendo DropDownList:
@(Html.Kendo().DropDownList()
.Name("concessions")
.HtmlAttributes(new { style = "width:320px" })
.DataTextField("Description")
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getConcessionsDDL", "MasterData");
});
})
)
The datasource is read from the getConcessionsDDL
method, in the controller:
public ActionResult GetConcessionsDDL()
{
ConcessionModel cm = new ConcessionModel();
var aux = cm.getConcessions();
return Json(aux.concessions.Select(sme => new ConcessionModel { Description = sme.concession.mediumDescription, Id = sme.concession.id }).Distinct(), JsonRequestBehavior.AllowGet);
}
It works fine, the DropDownList is populated as expected. But now I want define its default selected value. As it is now, the default value is always the first of the list.
I have used .SelectedIndex(4)
and it works: the selected index will be 4, in this case. But I want to define this in the controller.
I have tried to pass the selected index in a ViewBag
but no luck:
ViewBag.selectedIndex = 21;
And in the view:
@(Html.Kendo().DropDownList()
.Name("concessions")
.HtmlAttributes(new { style = "width:320px" })
.DataTextField("Description")
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getConcessionsDDL", "MasterData");
});
})
.SelectedIndex(ViewBag.selectedIndex)
)
No luck so far. Any help?
Upvotes: 2
Views: 4148
Reputation: 4412
The solution is simple, adding the value as an HTML attribute works fine:
.HtmlAttributes(new { value = ViewBag.ConcessionId })
Like this:
@(Html.Kendo().DropDownList()
.Name("concessions")
.HtmlAttributes(new { style = "width:320px" })
.DataTextField("Description")
.HtmlAttributes(new { value = ViewBag.ConcessionId })
.DataValueField("Id")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("getConcessionsDDL", "MasterData");
});
})
)
Upvotes: 4