C#ASP.net MVC中的DropDownlist和List问题

时间:2014-05-24 23:39:28

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

这是我的模特

public class StatModel
    {
            public IEnumerable<int> SelectedItemsRegion { set; get; }

            public List<string> SelectedStats { set; get; } // here I want to put selected Stats (value)

            public List<string> StatsList { set;  get; } //List of Values (stats) to select from it .

        public StatModel() 
            {
                StatsList = new List<string> {"agR", "demandeR" };
           }        

    }

这是我的观点:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>StatModel</legend>
        @Html.DropDownList("REGIONID", String.Empty)

        @Html.DropDownListFor(model=> model.SelectedStats, Model.StatsList as SelectList)
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

我收到错误@Html.DropDownListFor(model=> model.SelectedStats, Model.StatsList as SelectList)

  

CS0039:无法转换&#39; System.Collections.Generic.List&#39;至   &#39; System.Web.Mvc.SelectList&#39;

1 个答案:

答案 0 :(得分:1)

您无法将List<string>强制转换为SelectList,您需要初始化一个新的SelectList,例如

public SelectList SelectedStatsList { get; private set; } 

public StatModel() 
{
  StatsList = new List<string> {"agR", "demandeR" };
  SelectedStatsList = new SelectList(StatsList);
}

然后在视图中

@Html.DropDownListFor(model=> model.SelectedStats, Model.SelectedStatsList )