代码之家  ›  专栏  ›  技术社区  ›  Vlad

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

  •  0
  • Vlad  · 技术社区  · 8 年前

    我的剑道网格中有一个下拉列表列。我想将DataSource中的ViewData[“genres”]更改为GenreViewModel属性“AllGenres”。我该怎么做?别忘了我使用的是js版本的网格(不是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"]))
    

    我的下拉列表:

    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();
            }
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Vlad    8 年前

    斯蒂芬·穆克在评论中给出了答案。(不知道如何正确选择他的评论作为答案)

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

    但在我看来,我并没有声明一个模型,所以 我使用了我的静态属性:

    dataSource: @Html.Raw(Json.Encode(Number2.Models.GenreViewModel.GetAllGenres))