[英]How could I pass multiple collections to View as parameter from Controller in ASP.NET MVC?
I am trying to send a collection of data to a View from a Controller. 我正在尝试从控制器向视图发送数据集合。 I managed to make my code work with a single collection. 我设法使我的代码与单个集合一起工作。 Is it possible to achieve this with multiple collections (not using ViewBag but rather passing these as parameters to the View)? 是否可以通过多个集合(不使用ViewBag而是将这些作为参数传递给View)来实现?
What I tried: 我试过的
Controller 控制者
public ActionResult Index()
{
Dictionary<int, string> DictOne = MyObjOne.DictOne;
Dictionary<int, string> DictTwo= MyObjTwo.DictTwo;
return View(new { DictOne, DictTwo });
}
What I have (working already): 我所拥有的(已经在工作):
Controller 控制者
public ActionResult Index()
{
Dictionary<int, string> DictOne = MyObjOne.DictOne;
return View(DictOne);
}
View 视图
@model Dictionary<int, string>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list"></span>
Test
</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>
Test
</th>
</tr>
</thead>
<tbody>
@foreach (KeyValuePair<int, string> kvp in Model)
{
<tr>
<td>
@kvp.Value
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
How should I change the controller and view to pass these dictionaries? 如何更改控制器和视图以传递这些词典?
ViewModel
) 创建新的类(例如ViewModel
) ViewModel
with your dictionaries 用字典填充ViewModel
ViewModel
to view 传递ViewModel
进行查看 Example: 例:
public class ViewModel{
public Dictionary DictOne {get;set;}
public Dictionary DictTwo {get;set;}
}
public ActionResult Index()
{
Dictionary<int, string> DictOne = MyObjOne.DictOne;
Dictionary<int, string> DictTwo= MyObjTwo.DictTwo;
ViewModel model = new ViewModel(){
DictOne = DictOne,
DictTwo = DictTwo
};
return View(model);
}
View: 视图:
@model ViewModel
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list"></span>
Test
</div>
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>
Test
</th>
</tr>
</thead>
<tbody>
@foreach (KeyValuePair<int, string> kvp in Model.DictOne)
{
<tr>
<td>
@kvp.Value
</td>
</tr>
}
@foreach (KeyValuePair<int, string> kvp in Model.DictTwo)
{
<tr>
<td>
@kvp.Value
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
You can wrap the multiple dictionaries in a DataClass wrapper.Then in you View you can specify the class as 您可以将多个字典包装在DataClass包装器中。然后在View中可以将类指定为
View
@model Namespace.ClassName
Model
Class YourDataClass
{
Dictionary 1;
Dictionary 2;
}
Controller
Return View(object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.