如何在不使用ViewData的情况下将对象属性绑定到DropDownList中的数据源

问题描述 投票:0回答:1

我的kendo Grid中有一个DropDownList列。我想将DataSource中的ViewData [“genres”]更改为GenreViewModel属性“AllGenres”。我怎样才能做到这一点?不要忘记我使用js版本的Grid(不是mvc)。

我认为应该看起来像:

dataSource: @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize("AllGenres"))

要么

dataSource: "AllGenres"

反对:

dataSource: @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["genres"]))

我的DropDownList:

function genreDropDownEditor(container, options) {
    $('<input required name="' + options.field + '"/>')
        .appendTo(container)
        .kendoDropDownList({
            autoBind: false,
            dataTextField: "GenreName",
            dataValueField: "GenreId",
            dataSource: @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["genres"]))               
});
<script type="text/kendo" id="genresTemplate">
    #if(data.Genre != null)
    { #

    #: Genre.GenreName #

    # } #

我的GenreViewModel:

public class GenreViewModel
{
    public int GenreId { get; set; }
    public string GenreName { get { return Enum.GetName(typeof(Genre), GenreId); } }

    public static List<GenreViewModel> AllGenres
    {
        get
        {
            return Enum.GetValues(typeof(Genre)).Cast<Genre>().Select(v => new GenreViewModel
            {
                GenreId = ((int)v)
            }).ToList();
        }
    }
}
javascript c# jquery asp.net-mvc kendo-ui
1个回答
0
投票

Stephen Muecke在评论中给出了答案。(不知道如何正确选择他的评论)

dataSource: @Html.Raw(Json.Encode(Model.AllGenres)).

但我没有在我的视图中声明模型,所以我使用了我的静态属性:

dataSource: @Html.Raw(Json.Encode(Number2.Models.GenreViewModel.GetAllGenres))
© www.soinside.com 2019 - 2024. All rights reserved.