【问题标题】:Display list of strings显示字符串列表
【发布时间】:2015-05-07 02:01:06
【问题描述】:

我目前正在学习 C# .net,我正在尝试显示不同的状态列表,但我就是不知道如何做到这一点。

在我的控制器中,我有:

public ActionResult StateListDistinct()
        {
            var distinctStates = (from w in db.Contact_Addresses
                                  select new { State = w.Site_address_state}).Distinct();

            return View(distinctStates.ToList());
        }

在我看来,我有:

@model List<String>
<table class="table">

@foreach (var item in Model) {
    <tr>

        <td>
            @Html.DisplayFor(model => item)
        </td>

    </tr>
}

</table>

我收到了错误

传入字典的模型项的类型为“System.Collections.Generic.List`1[f__AnonymousType1`1[System.String]]”,但此字典需要“System.Collections”类型的模型项.Generic.List`1[System.String]'。

我需要做什么才能显示状态列表?

【问题讨论】:

  • select new w.Site_address_state 假设 Site_address_state 是字符串类型。

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


【解决方案1】:

您的视图需要一个字符串列表,但您输入的是一个匿名类型列表。

使用方法语法,您想要实现的目标可以通过这种方式完成:

db.Contact_Addresses.Select(state =>state.Site_address_state).Distinct().ToList();

这也应该可以解决问题:

var distinctStates = (from w in db.Contact_Addresses
                              select w.Site_address_state).Distinct().ToList();

【讨论】:

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