Asp.net 默认模型绑定器和包含列表的复杂类型
我正在使用ASP.NETMVC的RC1 我试图扩展模型绑定示例。我正在尝试使用默认模型绑定器绑定以下对象:Asp.net 默认模型绑定器和包含列表的复杂类型,asp.net,asp.net-mvc,binding,Asp.net,Asp.net Mvc,Binding,我正在使用ASP.NETMVC的RC1 我试图扩展模型绑定示例。我正在尝试使用默认模型绑定器绑定以下对象: public class ListOfProducts { public int Id { get; set; } public string Title{ get; set; } List<Product> Items { get; set; } } public class Product { public string Name { ge
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; }
}
产品的公共类列表
{
公共int Id{get;set;}
公共字符串标题{get;set;}
列表项{get;set;}
}
公共类产品
{
公共字符串名称{get;set;}
公共十进制价格{get;set;}
}
我使用Phil示例中的代码进行了一些修改:
控制器:
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; }
}
}
使用System.Collections.Generic;
使用System.Web.Mvc;
命名空间TestBinding.Controllers
{
[手机错误]
公共类HomeController:控制器
{
公共行动结果索引()
{
ViewData[“Message”]=“欢迎使用ASP.NET MVC!”;
返回视图();
}
//HomeController的动作方法
公共行动结果更新产品(产品列表产品列表)
{
返回视图(productlist);
}
}
公共类产品
{
公共字符串名称{get;set;}
公共十进制价格{get;set;}
}
公共类产品列表
{
公共int Id{get;set;}
公共字符串标题{get;set;}
列表项{get;set;}
}
}
视图:
主页
我的问题是简单类型(Id和标题)出现在productlist对象中,而不是列表中。因此:
- 我的代码是不是很糟糕(一点也不奇怪)
- 默认模型绑定器能否处理产品对象列表
- 如果默认的模型绑定器不能处理这种类型的对象,我需要做什么(如果可能,举例说明)
- 不再需要隐藏索引
- []中的数字必须以0开头,必须递增
另外,我注意到您在items属性名称上使用了不同的大小写。这应该没什么区别,但值得一查。回答我自己的问题: 我是个笨蛋 我的示例不起作用,因为ListOfProducts类的Items属性不是公共的:
public class ListOfProducts
{
public int Id { get; set; }
public string Title{ get; set; }
List<Product> Items { get; set; }
}
产品的公共类列表
{
公共int Id{get;set;}
公共字符串标题{get;set;}
列表项{get;set;}
}
我改变了:
List<Product> Items { get; set; }
列出项目{get;set;}
致:
公共列表项{get;set;}
然后我的代码就起作用了
总而言之,默认模型绑定器确实适用于包含类型列表属性的类型。您不是虚拟对象。我也有同样的问题,但那是因为我的列表不是一个属性。我有类似的东西:公共列表项,而不是公共列表项{get;set;}
List<Product> Items { get; set; }
public List<Product> Items { get; set; }