提问人:zeifi 提问时间:9/11/2015 最后编辑:marc_szeifi 更新时间:9/11/2015 访问量:469
如何在 ASP.NET MVC 中的同一网页上使用两个不同的模型显示两个视图
How to display two views using two different models on the same web page in ASP.NET MVC
问:
下面是控制器和视图的代码。我想在 MVC ASP.NET 同一网页上显示这两个视图。如何实现这一目标?
控制器:
public ActionResult LetterList()
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return View(obj);
}
public ActionResult Showimage(string ListId)
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return View(letterList);
}
LetterList 视图
@model LetterPage.Models.ModelView
<div>
@{
foreach (var item in Model.letterDetail)
{
<div>
<a href="/Home/[email protected]">@item.ListName</a>
</div>
}
}
</div>
ShowImage 视图:
@model IList< LetterPage.Models.hurf_e_tahaji>
@{
ViewBag.Title = "ShowImage";
}
<table class="table">
<tr>
<th>
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
<img src="@Url.Content("item.Letter_Pic") "/>
</td>
</tr>
}
</table>
当我将这些视图创建为分部视图并将它们呈现到另一个视图中时,模型的循环上发生了异常。Foreach
答:
0赞
Sirwan Afifi
9/11/2015
#1
您可以使用 PartialView:
[HttpPost]
public PartialViewResult LetterList()
{
if (Request.IsAjaxRequest())
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return PartialView(obj);
}
return null;
}
[HttpPost]
public PartialViewResult Showimage(string ListId)
{
if (Request.IsAjaxRequest())
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return PartialView(letterList);
}
return null;
}
然后你必须定义你的部分视图(就像你发布的代码),并在主视图中:
<div class="LetterList">
<img src="@Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
<div class="Showimage">
<img src="@Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
@section Scripts
{
<script type="text/javascript">
$(function () {
$.post('/Home/LetterList', function(data) {
$('.LetterList').html(data);
});
$.post('/Home/Showimage/' + ListId, function(data) {
$('.Showimage').html(data);
});
});
</script>
}
评论
@Html.Action("LetterList")
Showimage.cshtml
LetterList()