[英]ASP MVC3 - passing collection item into partial view
我有一个我用一个单独模型的集合( List
)创建的视图模型。 在我们的数据库中,我们有两个表: BankListMaster
和BankListAgentId
。 “主”表的主键用作代理ID表的外键。
由于主/代理ID表具有一对多关系,因此我创建的视图模型包含BankListAgentId
的List
对象。 在我们的编辑页面上,我希望既可以显示与特定银行关联的任何和所有代理ID,也可以让用户添加或删除它们。
我目前正在研究史蒂夫桑德森关于编辑可变长度列表的博客文章。 但是,从数据库中提取现有项目时似乎并未涵盖此特定方案。
我的问题是你可以将特定的集合项传递给局部视图,如果是这样,你会如何正确地将其编码到局部视图中? 以下代码说明了这一点
The name 'item' does not exist in the current context
但是,我也尝试在局部视图中使用带索引的常规for
循环和此语法:
model => model.Fixed[i].AgentId
但这只是告诉我在当前背景下i
不存在的名称。 使用任一方法都不会呈现视图。
以下是视图中的代码
@model Monet.ViewModel.BankListViewModel
@using (Html.BeginForm())
{
<fieldset>
<legend>Stat(s) Fixed</legend>
<table>
<th>State Code</th>
<th>Agent ID</th>
<th></th>
@foreach(var item in Model.Fixed)
{
@Html.Partial("FixedPartialView", item)
}
</table>
</fieldset>
}
这是局部视图
@model Monet.ViewModel.BankListViewModel
<td>
@Html.DropDownListFor(item.StateCode,
(SelectList)ViewBag.StateCodeList, item.StateCode)
</td>
<td>
@Html.EditorFor(item.AgentId)
@Html.ValidationMessageFor(model => model.Fixed[i].AgentId)
<br />
<a href="#" onclick="$(this).parent().remove();" style="float:right;">Delete</a>
</td>
这是视图模型。 它目前将固定/可变代理Id列表初始化为10,但这只是解决此页面启动和运行的一种解决方法。 最后,希望允许列表根据需要大小。
public class BankListViewModel
{
public int ID { get; set; }
public string BankName { get; set; }
public string LastChangeOperator { get; set; }
public Nullable<System.DateTime> LastChangeDate { get; set; }
public List<BankListAgentId> Fixed { get; set; }
public List<BankListAgentId> Variable { get; set; }
public List<BankListAttachments> Attachments { get; set; }
public BankListViewModel()
{
//Initialize Fixed and Variable stat Lists
Fixed = new List<BankListAgentId>();
Variable = new List<BankListAgentId>();
Models.BankListAgentId agentId = new BankListAgentId();
for (int i = 0; i < 5; i++)
{
Fixed.Add(agentId);
Variable.Add(agentId);
}
//Initialize attachment Lists
Attachments = new List<BankListAttachments>();
Attachments.Add(new BankListAttachments());
}
}
您的局部视图存在问题。 在主视图中,在循环中,您传递的是BankListAgentId
对象。 但是,部分视图的模型类型是@model Monet.ViewModel.BankListViewModel
。
此外,您尝试在部分视图中访问名为item
的变量(如果不存在)。 不要使用item
来访问您的数据,而是像在任何其他视图中一样使用Model
。 每个视图(甚至是部分视图)都有自己的模型类型。
您的部分视图应如下所示:
@model Monet.ViewModel.BankListAgentId
<td>
@Html.DropDownListFor(model => model.StateCode,
(SelectList)ViewBag.StateCodeList, Model.StateCode)
</td>
<td>
@Html.EditorFor(model => model.AgentId)
@Html.ValidationMessageFor(model => model.AgentId)
<br />
<a href="#" onclick="$(this).parent().remove();" style="float:right;">Delete</a>
</td>
您传递到部分视图的模型是BankListAgentId ---因为您在创建局部视图时循环遍历它们的集合。
到目前为止,你正在做的一切。 您循环遍历列表,为每个列表项调用partial,并将项目传递给partial。 您似乎缺少的部分是当您将项目传递给部分时,该项目将成为部分项目的模型。 所以你可以像在任何其他视图中那样与它进行交互,即@Model.BankName
, @Html.DisplayFor(m => m.BankName)
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.