Reputation: 1457
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)?
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?
Upvotes: 1
Views: 597
Reputation: 1264
ViewModel
)ViewModel
with your dictionariesViewModel
to viewExample:
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>
Upvotes: 5
Reputation: 11
You can wrap the multiple dictionaries in a DataClass wrapper.Then in you View you can specify the class as
View
@model Namespace.ClassName
Model
Class YourDataClass
{
Dictionary 1;
Dictionary 2;
}
Controller
Return View(object);
Upvotes: 1