首页 文章

C#ASP.NET MVC视图下拉编译错误CS0161

提问于
浏览
0
@model IEnumerable<Calendar.Models.CheckDays

<p>
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <th>
                    @Html.ActionLink("Create New", "Create")
                </th>
                <th>
                    @Html.DropDownListFor(model => model.DayOfWeek, htmlAttributes: new { @class = "form-control" })
                </th>
                <th>
                    <input type="button" value="Search" />
                </th>
            </tr>

        </table>
    }

</p>
   <tr>
        <th>
            @Html.DisplayNameFor(model => model.DayOfWeek)
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.DayOfWeek)
            </td>
            </td>
        </tr>
    }

我正在尝试创建一个下拉列表,以便我可以过滤索引结果,但我一直收到错误

“编译器错误消息:CS1061:'IEnumerable'不包含'DayOfWeek'的定义,并且没有可以找到接受类型'IEnumerable'的第一个参数的扩展方法'DayOfWeek'(您是否缺少using指令或程序集引用?)”

出错的行是

Html.DropDownListFor(model => model.DayOfWeek, htmlAttributes: new { @class = "form-control" })".

我是否需要在模型中执行某些操作或者是否存在语法错误?

1 回答

  • 0

    你误解了第一个参数是什么 . 这是指所选项目应该去的地方 . 它适用于selectedItem变量 . 查看此博客文章:https://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx . 您必须为模型创建单独的类,其中包含元素列表和变量SelectedDayOfWeek .

    型号类:

    public class CheckDaysViewModel 
    {
      public IEnumerable<CheckDays> CheckDays {get;set;}
      public IEnumerable<SelectListItem> CheckDaysAsSelectedList => this.CheckDays.Select(e => new SelectListItem(e.DayOfWeek, e.DayOfWeek));
      public CheckDays SelectedDay {get;set;}
    
    }
    

    CSHTML

    @model CheckDaysViewModel
    
    <p>
        @using (Html.BeginForm())
        {
            <table>
                <tr>
                    <th>
                        @Html.ActionLink("Create New", "Create")
                    </th>
                    <th>
                        @Html.DropDownListFor(m => m.SelectedDay, Model.CheckDaysAsSelectedList, null, htmlAttributes: new { @class = "form-control" })
                    </th>
                    <th>
                        <input type="submit" value="Search" />
                    </th>
                </tr>
    
            </table>
        }
    </p>
    
    <table>
    
    <tr>
        <th>
            @Html.DisplayNameFor(m => m.CheckDays.First().DayOfWeek)
        </th>
    </tr>
    
        @foreach (var item in Model.CheckDays)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.DayOfWeek)
                </td>
            </tr>
        }
    
    </table>
    

相关问题