【发布时间】:2017-05-11 13:38:08
【问题描述】:
我正在尝试将我的 ASP.NET MVC 项目从直接视图和模型更改为使用 ViewModel 中间层。基本上,我所做的包括让 Person 与零个或多个 Events 相关联。我正在更改为 ViewModel,因为我想在 Person 详细信息页面上放置一个部分视图,以显示所有相关的 Events。
我有一个 Person 模型类和一个用于 Event 的模型类,这是我的 ViewModel:
public class PersonEventViewModel
{
public PersonEventViewModel(Person person)
{
Person = person;
}
public Person Person { get; set; }
public IEnumerable<Event> Events { get; set; }
}
这对于转换我的单个记录页面非常有效。在诸如 Person Details 之类的页面上,我不得不将 @Html.DisplayFor(model => model.CreatedOn) 之类的行更改为 @Html.DisplayFor(model => model.Person.CreatedOn) 以便它可以正确找到属性,但它确实有效。然而,在我试图制作的局部视图中,我似乎无法让它们在那里显示模型的属性。它看起来或多或少是这样的:
@model IEnumerable<Proj.ViewModels.PersonEventViewModel>
<table class="table">
<tr>
<th>@Html.DisplayNameFor(model => model.RecordedOn)</th>
<th>@Html.DisplayNameFor(model => model.RecordedBy)</th>
<th>@Html.DisplayNameFor(model => model.Comments)</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.RecordedOn)</td>
<td>@Html.DisplayFor(modelItem => item.RecordedBy)</td>
<td>@Html.DisplayFor(modelItem => item.Comments)</td>
</tr>
}
这在直接使用事件模型时有效,但现在我在model 和属性之间添加什么似乎并不重要,它总是告诉我它无法解决它。
另外,我不确定如何将 ViewModel 传递给局部视图。我还没想好要放什么:
@Html.RenderPartial("_PersonEventList", ?????)
我尝试传递模型或模型信息的各种尝试都遇到了错误。
根据请求,这是我的详细信息页面的来源,我试图在其中放置事件的部分视图。
@model Proj.ViewModels.PersonEventViewModel
@{ ViewBag.Title = "Details"; }
<h2>Details</h2>
<div>
<h4>Person</h4> <hr/>
<dl class="dl-horizontal">
<dt>@Html.DisplayNameFor(model => model.Person.FirstName)</dt>
<dd>@Html.DisplayFor(model => model.Person.FirstName)</dd>
@*...and so on through the fields...*@
</dl>
</div>
<p> @Html.ActionLink("Edit Record", "Edit", new {id = Model.Person.PersonId}) </p>
@Html.RenderPartial("_PersonEventList", Model)
【问题讨论】:
-
你试过这样@Html.RenderPartial("_PersonEventList", (List
)ViewBag.data) -
我没有,但这仍然给我一个错误,类似于它之前所说的:
Cannot implicitly convert type 'void' to 'object'. Expression must return a value to render. -
试试这样的,@Html.Partial("View", Model); @{Html.RenderPartial("viewName", Model));}
-
是的,那也没用。关于
void to object的第一部分相同,然后是Argument type 'Proj.ViewModels.PersonEventViewModel' is not assignable to model type 'IEnumerable<Proj.ViewModels.PersonEventViewModel>' -
显示查看页面的完整代码你在哪里调用了@Html.RenderPartial
标签: asp.net-mvc partial-views asp.net-mvc-viewmodel