Kendo DropDownList默认选中的值

时间:2014-08-12 15:09:30

标签: asp.net-mvc razor kendo-ui

我有一个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");
        });
    })
)

从控制器中的getConcessionsDDL方法读取数据源:

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);
}

它工作正常,DropDownList按预期填充。但是现在我想要定义它的默认选择值。就像现在一样,默认值始终是列表中的第一个。

我使用了.SelectedIndex(4)并且它有效:在这种情况下,所选索引将为4。但我想在控制器中定义它。

我试图在ViewBag中传递所选索引,但没有运气:

ViewBag.selectedIndex = 21;

在视图中:

@(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)
)

到目前为止没有运气。有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

解决方案很简单,将值添加为HTML属性可以正常工作:

.HtmlAttributes(new { value = ViewBag.ConcessionId })

像这样:

@(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");
        });
    })
)