【问题标题】:How to show variables of class (IN MVC Model) in a view in dropdownlist如何在下拉列表的视图中显示类的变量(IN MVC 模型)
【发布时间】:2019-08-30 05:27:05
【问题描述】:

我有一个名为 contract_detail 的模型类,它们是此类中的一个名为 season 的字段我创建了另一个类,并在这个新类中定义了季节字段现在我想在视图中显示新类的所有变量在下拉列表中。

<div class="form-group">
            @Html.LabelFor(model => model.Season, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Season, new SelectList(Enum.GetValues(typeof(Season)), new { @class = "form-control" })

                @*@Html.EditorFor(model => model.Season, new { htmlAttributes = new { @class = "form-control" } })*@
                @Html.ValidationMessageFor(model => model.Season, "", new { @class = "text-danger" })
            </div>
        </div>
//My season class which define field season
public class Season
    {
        public Season(string value) { Value = value; }

        public string Value { get; set; }

        public static Season S1 { get { return new Season("2018-2019"); } }
        public static Season S2 { get { return new Season("Debug"); } }
        public static Season S3 { get { return new Season("Info"); } }
        public static Season S4 { get { return new Season("Warning"); } }
        public static Season S5 { get { return new Season("Error"); } }
    }

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4


    【解决方案1】:

    只关注下拉列表,您当前的代码不起作用,原因有几个。主要是,您定义的 Season 类是一个类而不是 Enumeration,因此 Enum.GetValues(typeof(Season)) 将无法正常工作。

    我会考虑重构您的视图模型。您可能需要更新其他表单输入以适应此视图模型,但它应该适用于您希望实现的下拉列表。

    @model ViewModel
    <div class="form-group">
        @Html.LabelFor(model => model.Season, htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
            @Html.DropDownListFor(model => model.SelectedSeason, Model.SeasonList, new { @class = "form-control" })
            @*@Html.EditorFor(model => model.Season, new { htmlAttributes = new { @class = "form-control" } })*@
            @Html.ValidationMessageFor(model => model.Season, "", new { @class = "text-danger" })
        </div>
    </div>
    
    public class ViewModel
    {
        public string SelectedSeason { get; set; }
        public IEnumerable<Season> Seasons { get; set; }
        public SelectList SeasonList { get; set; }
    
        public ViewModel() 
        {
            Seasons = new List<Season>() 
            {
                { new Season("2018-2019") },
                { new Season("Debug") },
                { new Season("Info") },
                { new Season("Warning") },
                { new Season("Error") },
            };
    
            SeasonList = new SelectList(Seasons, "Value", "Value");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多