gpt4 book ai didi

c# - 如何在 asp.net MVC 中映射 2 个不同的列表

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

我试图将一个列表从 Controller 发送到 View。我以为它会绑定(bind),但它是不同的类型,所以不会。 (错误:参数类型“System.Collections.Generic.List”不可分配给模型类型“System.Collections.Generic.IEnumerable”)。那么我应该如何映射这两个列表呢?

Controller

 public ActionResult MyData()
{
var oldList = db.oldList.Select(x=>x.Name).ToList();

// probably here i should add var newList and in some way map with oldList then return to view

return View(oldList);
}

新建列表ViewModel

 public class NewListViewModel
{
public string Name { get; set; }
public int Count { get; set; }
}

我的 View (我的数据)

@model IEnumerable<MyApp.ViewModels.NewListViewModel>

<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Count)
</th>
</tr>

@foreach (var item in Model)
{
using (Html.BeginForm())
{
<tr>
<td>
@Html.TextBoxFor(modelItem => item.Name)
</td>
<td>
@Html.TextBoxFor(modelItem => item.Count)
</td>
</tr>
}
}
</table>

最佳答案

你几乎成功了:

    public ActionResult MyData()
{
List<NewListViewModel> newList =
db.oldList.Select(x=>new NewListViewModel { Name = x.Name}).ToList();

return View(newList);
}

关于c# - 如何在 asp.net MVC 中映射 2 个不同的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35017484/

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