【问题标题】:System.Collections.Generic.List MVC ErrorSystem.Collections.Generic.List MVC 错误
【发布时间】:2015-05-05 14:28:40
【问题描述】:

我想查看Edit.cshtml中的表格 我使用Html.ActionSurveyQuestionController 获取表格,但它显示错误如下:

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

我有什么不对吗??

编辑.cshtml:

@model SurveyTool.Models.SurveyModel
<div>
    <h2>Link</h2>
    @Html.Action("QuestionLink", "SurveyQuestion", new { id = Model.SurveyID })
</div>

SurveyQuestionController.cs:

public ActionResult QuestionLink(string SurveyID)
{
    var query = (from r in db.SurveyQuestionModels
                 where r.SurveyId == SurveyID
                 select r.QuestionLink).Distinct();

    return PartialView(query.ToList());
}

QuestionLink.cshtml:

 @model IEnumerable<SurveyTool.Models.SurveyQuestionModel>
 <br />     
 <table class="strip">
     @foreach (var item in Model)
     {
         <tr>
             <td>@Html.DisplayFor(modelitem => item.QuestionLink)</td>
         </tr>
     }
 </table>

SurveyQuestionModel.cs:

namespace SurveyTool.Models
{
    public class SurveyQuestionModel
    {
        public int Id { get; set; }
        public string QuestionLink { get; set; } 
    }
}

【问题讨论】:

    标签: asp.net-mvc-4 razor


    【解决方案1】:

    您的查询仅选择SurveyQuestionModelQuestionLink 属性(由您使用select r.QuestionLink),这是string 的类型,因此当视图需要List&lt;SurveyQuestionModel&gt;

    更改查询以返回SurveyQuestionModel 的集合

    public ActionResult QuestionLink(string SurveyID)
    {
        var query = (from r in db.SurveyQuestionModels
                     where r.SurveyId == SurveyID
                     select r);
    
        return PartialView(query.ToList());
    }
    

    或更改视图,使模型为List&lt;string&gt;

    @model List<string>
    
    @foreach (var item in Model)
    {
        @Html.DisplayFor(modelitem => item)
    }
    

    【讨论】:

    • 嗨,斯蒂芬,感谢您的回答,但我只想选择唯一的结果。这就是为什么我使用不同的。无论如何要解决这个问题?
    • 由于您的视图只显示QuestionLink 值,请使用第二个选项,否则您需要修改查询
    • This article 为您提供了一些选项,用于根据模型中仅一个属性的不同值生成集合。
    • 非常感谢斯蒂芬,我使用了第二个选项,它有效!非常有用的信息!
    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多