MVC C# Dropdown list Showing System.Web.SelectListItem on the model and can not blind to controller

前端 未结 1 1171
陌清茗
陌清茗 2021-01-23 07:27

Please help me. My dropdownlist showing System.Web.SelectListItem in debug mode but not showing actual text that I defined in the list. Can anyone please help. How

相关标签:
1条回答
  • 2021-01-23 07:35

    Follow below technique in which populate your SelectList from your controller. Its simple and clean:

    Model

    public string KeywordOptionsSelected { get; set; }
    public SelectList KeywordOptions { get; set; }
    

    Controller

    model.KeywordOptions = new SelectList(new List<SelectListItem> { 
                            new SelectListItem { Value = "TEST 1", Text = "Market Cap" },
                            new SelectListItem { Value = "TEST 2", Text = "Revenue" },
                            }, "Value", "Text");
    

    View

    @Html.DropDownListFor(model => model.KeywordOptionsSelected, Model.KeywordOptions, "--Select Option--", new { @id = "Dropdown_TEST" })
    

    In this way, the code is easy to understand and View is also clean as all SelectList will be populated from cs.

    You can make it more cleaner by populating SelectLists separately in methods and call in model.KeywordOptions to populate it.

    public static List<SelectListItem> GetKeywords()
    {
        var keyword = new List<SelectListItem>();
        keyword.Add(new SelectListItem { Value = "TEST 1", Text = "Market Cap" });
        keyword.Add(new SelectListItem { Value = "TEST 2", Text = "Revenue" });
        return keyword;
    }
    model.KeywordOptions = new SelectList(GetKeywords(), "Value", "Text");
    
    0 讨论(0)
提交回复
热议问题