繼承這是我的模型ASP.NET MVC模型綁定返回null時模型的種類從CollectionBase的
public class MessageSetTypeCollection<T> : CollectionBase where T : MessageSetType, new()
{
public string Name { get; set; }
public string[] Tags { get; set; }
public MessageSetType this[int index]
{
get
{
return (MessageSetType)List[index];
}
}
public void Add(MessageSetType value)
{
List.Add(value);
}
}
這是我的控制器動作
public ActionResult TestAction()
{
MessageSetTypeCollection<MessageSetType> Model = new MessageSetTypeCollection<MessageSetType>();
Model.Add(new MessageSetType()
{
Alert = "test" // Alert is a public property of the MessageSetType class
});
Model.Add(new MessageSetType()
{
Alert = "test2"
});
return View(Model);
}
[HttpPost]
public void TestAction(MessageSetTypeCollection<MessageSetType> Model)
{
return;
}
在我有這個代碼視圖
@using (Html.BeginForm())
{
@Html.EditorFor(a => a[0].Alert)
@Html.EditorFor(a => a[1].Alert)
<input type="submit" value="OK" />
}
當我將此表單提交給TestAction操作時,Model參數的內部列表的計數爲0個元素TS。爲什麼?
我還測試了這款代碼List<MessageSetType>
模型類型,而不是MessageSetTypeCollection<MessageSetType>
和所有工作正常。錯誤在哪裏?
是的,問題是,'CollectionBase'是'abstract'和'DefaultModelBinder'無法初始化一個抽象類的實例(內部它使用'Activator.CreateInstance()') –