0%

【MVC】One View Two Models -- tuple or ViewModel

如果有個View同時需要載入兩個model時可以使用tuple ```html
@model Tuple<IEnumerable<NTI.Models.ExhibitionList>,NTI.Models.ExhibitionList>

1
2
3
4
5
6
7
8
9
10
11
12
13
14


**Model**```csharp
public class ExhibitionList
{
[Required]
[MaxLength(50)]
public string ExhibitionName { get; set; }

public DateTime CreateDate { get; set; }

public DateTime EditDate { get; set; }
}

Controller```csharp
public ActionResult ExhibitionList()
{
var tuple = new Tuple<IEnumerable, ExhibitionList>(Repository.GetExhibitionList(), new ExhibitionList());
return PartialView(tuple);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

**View**```html
if (Model.Item1.Count() == 0)
{
<tr id="noExhibition">
<td colspan="4">
<span class="text-left">沒有建立任何展覽喔....</span>
</td>
</tr>
}
else
{
foreach (var exhibitionItem in Model.Item1)
{
<tr>
<td>1</td>
<td>@exhibitionItem.ExhibitionName</td>
<td>@exhibitionItem.CreateDate</td>
<td>@exhibitionItem.EditDate</td>
</tr>
}
@Html.TextBoxFor(m => Model.Item2.ExhibitionName)
}

在View中使用Model的方法為:
Model.Item1代表載入的第一個Model
Model.Item2代表載入的第二個Model

第二種方式就是建立一個ViewModel的方式
Model```csharp
/// 展覽列表的ViewModel
public class ExhibitionListViewModel
{
public IEnumerable IEmumerable_ExhibitionList { get; set; }
public ExhibitionList ExhibitionListModel { get; set; }
}

1
2
3
4
5
6
7
8
9
**View**```csharp
public ActionResult ExhibitionList()
{
ExhibitionListViewModel model = new ExhibitionListViewModel();
model.IEmumerable_ExhibitionList = Repository.GetExhibitionList();
model.ExhibitionListModel = new ExhibitionList();
return PartialView(model);
}

Controller```csharp
@Html.TextBoxFor(model => model.ExhibitionListModel.ExhibitionName)
@Html.ValidationMessageFor(model => model.ExhibitionListModel.ExhibitionName)

//and ….
if (Model.IEmumerable_ExhibitionList.Count() == 0)
{
//do something
}