我正在使用ASP.NET MVC的RC1。默認模型聯編程序和包含列表的複雜類型
我試圖擴展Phil Haack's模型綁定的例子。我試圖使用默認的模型綁定綁定以下對象:
public class ListOfProducts
{
public int Id { get; set; }
public string Title{ get; set; }
List<Product> Items { get; set; }
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
我用菲爾的例子有一些改動代碼:
控制器:
using System.Collections.Generic;
using System.Web.Mvc;
namespace TestBinding.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
//Action method on HomeController
public ActionResult UpdateProducts(ListOfProducts productlist)
{
return View(productlist);
}
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ListOfProducts
{
public int Id { get; set; }
public string Title { get; set; }
List<Product> Items { get; set; }
}
}
查看:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexHead" ContentPlaceHolderID="head" runat="server">
<title>Home Page</title>
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<form method="post" action="/Home/UpdateProducts">
<input type="text" name="productlist.id" value="99" />
<input type="text" name="productlist.Title" value="SomeTitle" />
<input type="hidden" name="productlist.Index" value="0" />
<input type="text" name="productlist.items[0].Name" value="Beer" />
<input type="text" name="productlist.items[0].Price" value="7.32" />
<input type="hidden" name="productlist.Index" value="1" />
<input type="text" name="productlist.Items[1].Name" value="Chips" />
<input type="text" name="productlist.Items[1].Price" value="2.23" />
<input type="hidden" name="productlist.Index" value="2" />
<input type="text" name="productlist.Items[2].Name" value="Salsa" />
<input type="text" name="productlist.Items[2].Price" value="1.23" />
<input type="submit" />
</form>
</asp:Content>
我的問題是,簡單類型(Id和標題)出現在productlist對象中ct,但不是列表。所以:
- 是我的代碼壞(不會感到驚訝)?
- 默認模型聯編程序可以處理ListOfProducts對象嗎?
- 如果默認的模型聯編程序不處理這種類型的對象我需要做什麼(如果可能的話)?
在此先感謝。
嗨克雷格,感謝您的提示,非常感謝。 – 2009-03-06 08:36:18
+1已保存我的日子 – alexandrul 2009-05-11 16:49:57