【发布时间】:2011-11-10 20:59:23
【问题描述】:
我已经搜索了高低,希望有人可以帮助我。我有一堂课:
public class Person
{
public string Name { get; set; }
public ICollection<Toys> { get; set; }
}
我有一个控制器方法:
public ActionResult Update(Person toycollector)
{
....
}
我想绑定到集合。我意识到我只会得到 ID,但我会在我的控制器中处理它。我只需要能够翻阅 ID 的集合。我开始编写模型活页夹:
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(ICollection<Toys>))
{
//What do I do here???
}
}
那么,如何根据传递给我的方法的值构建玩具集合?谢谢!
编辑: 看起来我无法将这个答案发布到我自己的问题上,所以我将编辑我的帖子。看起来您所要做的就是解析数据并将其添加到模型中,如下所示:
if (propertyDescriptor.PropertyType == typeof(ICollection)) {
var incomingData = bindingContext.ValueProvider.GetValue("Edit." + propertyDescriptor.Name + "[]");
if (incomingData != null)
{
ICollection<Toy> toys = new List<Toy>();
string[] ids = incomingData.AttemptedValue.Split(',');
foreach (string id in ids)
{
int toyId = int.Parse(id);
toys.Add(new Toy() { ToyID = toyId });
}
var model = bindingContext.Model as Person;
model.Toys = toys;
}
return;
}
【问题讨论】:
-
您现在可以尝试添加答案吗?
标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2