ASP MVC传递非顺序项
本文关键字:顺序 MVC ASP | 更新日期: 2023-09-27 17:59:51
我有一个包含public List<Room> Rooms { get; set; }
的视图模型Rooms包含一个List<BL.Image> Images
。在我的视野中,我循环浏览房间并显示每张图像。
for (int i = 0; i < Model.Rooms.Count; i++)
{
@for (var ii = 0; ii < Model.Rooms[i].Images.Count; ii++)
{
<div class="slide">
<img class="pic panel" src="@Url.Content(Model.Rooms[i].Images.ToList()[ii].Path)" />
@{ ViewBag.Imageindex = "Rooms[" + i + "].Images[" + ii + "].Index"; }
<input type="hidden" name="@ViewBag.ImageIndex" value="@Html.Raw(ii)" />
@*also tried<input type="hidden" name="@ViewBag.ImageIndex" value="" />also tried*@
@Html.HiddenFor(m => Model.Rooms[i].Images.ToList()[ii].ImageID, new { Name = "Rooms[" + i + "].Images[" + ii + "].ImageID" })
@Html.HiddenFor(m => Model.Rooms[i].Images.ToList()[ii].Path, new { Name = "Rooms[" + i + "].Images[" + ii + "].Path" })
<div class="snipit">
<img class="hoverpic panel" src="http://findicons.com/files/icons/99/office/128/delete.png" width="40" height="40" />
</div>
</div>
}
}
用户可以添加或删除图像,但如果图像被删除,则在提交表单时,只有在识别删除图像之前的图像,例如
显示图像1、图像2、图像3、图像4
图像3被删除
当提交表单时,仅识别图像1和2。
为了解决这个问题,我审查了一个问题,我似乎也在做同样的事情。这个问题还链接到了这篇博客文章——接近尾声时,它涵盖了非序列指数
非连续指数…当您不能保证提交的值将保持顺序索引时,会发生什么?例如,假设您希望允许在通过JavaScript提交图书列表之前删除行。好消息是,通过引入额外的隐藏输入,您可以允许任意索引。在下面的示例中,我们为需要绑定到列表的每个项提供一个带有.Index后缀的隐藏输入。每个隐藏输入的名称都是相同的。。。这将为模型绑定器提供一个很好的索引集合,以便在绑定到列表时查找。
<form method="post" action="/Home/Create">
<input type="hidden" name="products.Index" value="cold" />
<input type="text" name="products[cold].Name" value="Beer" />
<input type="text" name="products[cold].Price" value="7.32" />
<input type="hidden" name="products.Index" value="123" />
<input type="text" name="products[123].Name" value="Chips" />
<input type="text" name="products[123].Price" value="2.23" />
<input type="hidden" name="products.Index" value="caliente" />
<input type="text" name="products[caliente].Name" value="Salsa" />
<input type="text" name="products[caliente].Price" value="1.23" />
<input type="submit" />
不幸的是,我们没有生成这些隐藏输入的助手。
我做错了什么?
名称为Rooms.Index
和Rooms[i].Images.Index
的集合索引器需要2个隐藏输入。此外,不要尝试更改HtmlHelper
方法生成的name
属性。你的代码应该是
for (int i = 0; i < Model.Rooms.Count; i++)
{
<input type="hidden" name="Rooms.Index" value="@i" /> // outer indexer
@for (var ii = 0; ii < Model.Rooms[i].Images.Count; ii++)
{
<input type="hidden" name="Rooms[@i].Images.Index" value="@ii" /> // inner indexer
<div class="slide">
<img class="pic panel" src="@Url.Content(Model.Rooms[i].Images.ToList()[ii].Path)" />
@Html.HiddenFor(m => Model.Rooms[i].Images[ii].ImageID)
@Html.HiddenFor(m => Model.Rooms[i].Images[ii].Path)
<div class="snipit">
<img class="hoverpic panel" src="http://findicons.com/files/icons/99/office/128/delete.png" width="40" height="40" />
</div>
</div>
}
}