这个问题困扰我已经两天了。有一些类似的帖子,但没有一个完全解决我的问题。
使用MVC-3,Razor语法:
-- EDIT.cshtml --
@using (Html.BeginForm("Edit", "My", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Some fields... -->
<div class="editor-field">
@Html.TextAreaFor(m => m.LongDescription)
@Html.ValidationMessageFor(m => m.LongDescription)
</div>
<!-- Some more fields work... Including picture upload (summary).-->
<input name="button" type="submit" value="Add Picture" />
<!-- Picture Item display -->
@foreach(var thumbnail in Model.ThumbnailImagePathAndNames)
{
<img src="@Url.Content(@thumbnail.ThumbnailPicturePath)" alt="" width="200" />
@Html.RadioButtonFor(o=>o.SelectedImage, @thumbnail.ImageGUID) Primary Picture
<!-- Checkbox to mark for deletion -->
@Html.CheckBoxFor(o=>thumbnail.Delete) Delete ???????? <!---- Here is a problem - I don't understand how this should work -->
}
<input id="Submit1" name="button" type="submit" value="Complete Edit!" />
}
-- 我的控制器.cs --
[HttpPost]
public ActionResult Edit(String button, HttpPostedFileBase file, MyMainModel model)
{
// if button = submit picture, work with picture here and break(long story)
// save model data
// if valid, save and redirect
// not valid or error, load up view like normal but with error messages
model.LoadThumbnails();
return View(model);
}
-- MyMainModel.cs --
public class MyMainModel
{
// some properties...
public Guid? SelectedImage { get; set; }
[Display(Name = "Detailed Description")]
public String LongDescription { get; set; }
// some more properties....
// and finally my list of models
public IList<ThumbnailModel> ThumbnailImagePathAndNames { get; set; }
public void LoadThumbnails()
{
// load up initial thumbnail models
this.ThumbnailImagePathAndNames = new List<ThumbnailModel>(readDataService.GetThumbnailModels(this.SomeID));
}
}
-- 缩略图模型.cs --
public class ThumbnailModel
{
public Guid ImageGUID { get; set; }
public String FullSizePicturePath { get; set; }
public String ThumbnailPicturePath { get; set; }
public bool Delete { get; set; }
}
那么问题出在哪里呢?当按下“Complete Edit!”按钮时,MyController的Edit被调用,如预期地保留了所有MyMainModel的数据……除了ThumbnailModel列表 - 它们变成了null。
应该如何解决这个问题?我尝试了许多不同的方法,包括制作可编辑模板和使用EditFor(o=>...,但都没有成功(这变得很困惑,因为我不知道EditFor是针对整个集合还是仅针对集合中的单个项 - 我两种方式都尝试了)。所有这些方法在添加复选框以进行删除时仍然有效,因此需要检索ThumbnailModels列表以检查内部Delete属性值。
感谢您的阅读和尝试理解。
[免责声明 - 一些变量和方法名称已更改以保护无辜程序。许多代码已被剥离并替换为注释代码。]
thumbnail=>thumbnail.Delete
吗? - Buildstarted