asp.net-mvc - Kendo DropDownList 默认选定值

标签 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");
        });
    })
)

数据源是从 Controller 中的 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。但我想在 Controller 中定义它。

我尝试在 ViewBag 中传递选定的索引,但没有成功:

ViewBag.selectedIndex = 21;

在 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)
)

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

最佳答案

解决方案很简单,将值添加为 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");
        });
    })
)

关于asp.net-mvc - Kendo DropDownList 默认选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267897/

相关文章:

c# - 为什么 Razor 没有添加适当的 Bootstrap 类来形成控件?

asp.net-mvc-3 - asp.net mvc 3 Razor 部分和可移植区域

sorting - 剑道网格服务器端过滤并且不工作

charts - 如何在剑道图表中应用平面颜色效果

c# - 将 .NET 日期/时间格式字符串转换为 Javascript 日期/时间格式字符串

asp.net-mvc - 如何使用 Automapper 进行统一依赖注入(inject)?

json - 寻找通过 razor @Html.Raw(Json.Encode(Model)) 将 json 数据从 asp.net mvc 4.5 传递到 angular 2 组件的解决方案

jquery - 对自定义属性执行客户端验证

asp.net - WindowsAzure html utf-8 编码问题

c# - 检查字符串以获得足够强的密码