gpt4 book ai didi

c# - 在 View 中声明@model List 并将 LINQ 查询结果发送给它会导致错误

转载 作者:行者123 更新时间:2023-11-30 23:20:11 26 4
gpt4 key购买 nike

在我的 ASP.NET MVC Core 应用程序中,如果我传递下面查询 1 和查询 2 的 LINQ 查询结果,我会收到以下错误。另一方面,如果我传递 LINQ 查询 3 的结果,我会正确显示 View 而不会出现任何错误。但是查询 3 正在发送 Blogs 表的所有列,而我只想发送这些列我想在 View 中显示。 问题:如何在仅将要在 View 中显示的列发送到 View 时避免出现以下错误?

注意:我想避免使用 ViewModel,因为我在 LINQ 查询中只使用一个表。此外,显然查询是从 Action 方法发送的,为了简洁起见,我没有在此处包含该方法:

错误:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List'1[<>f__AnonymousType3`3[System.Int32,System.String,System.Boolean]]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List'1[myProj.Models.Blog]'

LINQ 查询 1:

var qry = from b in _context.Blogs
select new {b.BlogId, b.BlogName, b.IsNotified};
return View(await qry.ToListAsync());

LINQ 查询 2:

var qry = from b in _context.Blogs
select new { BlogId= b.BlogId, BlogName= b.BlogName, IsNotified = b.IsNotified};

return View(await qry.ToListAsync());

LINQ 查询 3:

var qry = from b in _context.Blogs
select b;
return View(await qry.ToListAsync());

查看:

@model List<myProj.Models.Blogs>
<form asp-controller="DbRelated" asp-action="BlogsReview" method="post">
<table class="table">
<thead>
<tr>
<th></th>
<th>
Blog Name
</th>
<th>
Is Notified
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.HiddenFor(r => r[i].BlogId)</td>
<td>
@Html.EditorFor(r => r[i].BlogName)
</td>
<td>
@Html.CheckBoxFor(r => r[i].IsNotified)
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-default">Save</button>
</form>

最佳答案

错误是因为您返回给 View 的类型与 View 期望的类型不同。

我建议您创建一个 ViewModels 文件夹,然后创建一个 ViewModel class在文件夹中,它基本上是一个类,其中仅包含您将在 View 中使用的属性,然后更改 View 中的模型类型。

ViewModel 可能看起来像这样

public class BlogViewModel 
{
public int Id {get; set;}
public string Name {get; set;}
public bool IsNotified {get; set;}
}

linq 查询

var viewModelList = new List<BlogViewModel>();
_context.Blogs.ForEach(b =>
{
viewModelList.Add(new BlogViewModel
{
Id = b.BlogId,
Name = b.BlogName,
IsNotified = b.IsNotified
});
});
return View(viewModelList);

风景

@model IEnumerable<MyProject.ViewModels.BlogViewModel>
<form asp-controller="DbRelated" asp-action="BlogsReview" method="post">
<table class="table">
<thead>
<tr>
<th></th>
<th>
Blog Name
</th>
<th>
Is Notified
</th>
</tr>
</thead>
<tbody>
@foreach (var blog in Model)
{
<tr>
<td>@Html.HiddenFor(r => r.Id)</td>
<td>
@Html.EditorFor(r => r.Name)
</td>
<td>
@Html.CheckBoxFor(r => r.IsNotified)
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-default">Save</button>

关于c# - 在 View 中声明@model List<className> 并将 LINQ 查询结果发送给它会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com