如何在 asp.net MVC 中映射 2 个不同的列表
How to map 2 diffrent List in asp.net MVC
我试图将列表从 Controller 发送到 View。我以为它会绑定,但它是不同的类型,所以不会。 (错误:参数类型 'System.Collections.Generic.List' 不可分配给模型类型 'System.Collections.Generic.IEnumerable')。那么我应该如何映射这两个列表?
控制器
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; }
}
我的视图 (MyData)
@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>
只需新建 List
of NewListViewModel
class 然后用 oldList 数据填充它
public ActionResult MyData()
{
var oldList = db.oldList.Select(x=>x.Name).ToList();
var newList=new list<NewListViewModel>();
foreach(var item in oldList)
{
newList.Add(new NewListViewModel{Name=item.Name});
}
return View(newList);
}
您可以按照@arash.zh 的建议进行操作。或者你可以只使用
@model dynamic
而不是
@model IEnumerable<MyApp.ViewModels.NewListViewModel>
你几乎成功了:
public ActionResult MyData()
{
List<NewListViewModel> newList =
db.oldList.Select(x=>new NewListViewModel { Name = x.Name}).ToList();
return View(newList);
}
我试图将列表从 Controller 发送到 View。我以为它会绑定,但它是不同的类型,所以不会。 (错误:参数类型 'System.Collections.Generic.List' 不可分配给模型类型 'System.Collections.Generic.IEnumerable')。那么我应该如何映射这两个列表?
控制器
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; }
}
我的视图 (MyData)
@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>
只需新建 List
of NewListViewModel
class 然后用 oldList 数据填充它
public ActionResult MyData()
{
var oldList = db.oldList.Select(x=>x.Name).ToList();
var newList=new list<NewListViewModel>();
foreach(var item in oldList)
{
newList.Add(new NewListViewModel{Name=item.Name});
}
return View(newList);
}
您可以按照@arash.zh 的建议进行操作。或者你可以只使用
@model dynamic
而不是
@model IEnumerable<MyApp.ViewModels.NewListViewModel>
你几乎成功了:
public ActionResult MyData()
{
List<NewListViewModel> newList =
db.oldList.Select(x=>new NewListViewModel { Name = x.Name}).ToList();
return View(newList);
}