【发布时间】:2009-07-29 17:47:29
【问题描述】:
我目前正在使用 EntityFramework 将我的 ASP.NET MVC 项目绑定到 MySQL 数据库,并且我的一个实体 Product 具有包含 ProductImage 集合的 Images 属性。我已经构建了一个表单以允许用户修改给定的产品,并且该表单还包括用于编辑与该产品关联的所有图像的字段。在阅读了Phil Haack's 和Dan Miser's 关于此事的帖子后,我对需要发生的事情有了一个不错的了解,但由于某种原因我似乎无法让它发挥作用......
这是我的产品表单:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KryptonCMS.Models.Product>" %>
<%@ Import Namespace="KryptonCMS.Core" %>
<%@ Import Namespace="KryptonCMS.Models.ViewModels" %>
<% using (Html.BeginForm())
{%>
<ul class="gallery">
<%
var index = 0;
foreach (var image in Model.ImageList.OrderBy(p => p.Order))
{
%>
<li>
<% Html.RenderPartial("ProductImageForm", image, new ViewDataDictionary(ViewData) { { "index", index } }); %>
</li>
<%
index++;
}
%>
</ul>
<p>
<input type="submit" name="btnSave" value="Save" />
<input type="submit" name="btnCancel" value="Cancel" />
</p>
<% } %>
这是 ProductImageForm 的定义:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KryptonCMS.Models.ProductImage>" %>
<%@ Import Namespace="KryptonCMS.Core" %>
<div>
<%
var fieldPrefix = string.Format("images[{0}]", ViewData["index"]); %>
<%=Html.Hidden(fieldPrefix + "ID", Model.ID) %>
<img src="<%=UtilityManager.GetProductImagePath(Model.Product.ID, Model.FileName, true) %>"
alt="" /><br />
<label for="Description">
Description:</label>
<%=Html.TextBox(fieldPrefix + "Description", Model.Description) %><br />
<label for="Order">
Order:</label>
<%=Html.TextBox(fieldPrefix + "Order", Model.Order)%><br />
</div>
最后是我的 ProductsController 操作:
public ActionResult Edit(int id)
{
var product = productsRepository.GetProduct(id);
if (product == null)
return View("NotFound", new MasterViewModel());
// else
return View(ContentViewModel.Create(product));
}
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Edit(int id, FormCollection formCollection)
{
var product = productsRepository.GetProduct(id);
if (formCollection["btnSave"] != null)
{
if (TryUpdateModel(product) && TryUpdateModel(product.Images, "images"))
{
productsRepository.Save();
return RedirectToAction("Details", new { id = product.ID });
}
return View(ContentViewModel.Create(product));
}
// else
return RedirectToAction("Details", new { id = product.ID });
}
单个 ProductImageForm 的 HTML 输出如下所示:
<div>
<input id="images[0]ID" name="images[0]ID" type="hidden" value="1" />
<img src="/Content/ProductGallery/3/thumbs/car1.jpg"
alt="" /><br />
<label for="Description">
Description:</label>
<input id="images[0]Description" name="images[0]Description" type="text" value="FAST CAR" /><br />
<label for="Order">
Order:</label>
<input id="images[0]Order" name="images[0]Order" type="text" value="1" /><br />
</div>
我尝试了各种重组表单的方法,包括将图像集合从产品表单中取出并将其放置在自己的表单中(我真的不想这样做),但没有任何效果。我的方法有什么明显的错误吗?
【问题讨论】:
标签: asp.net asp.net-mvc entity-framework binding model