C# 模型绑定到列表抛出“;“收藏是只读的”;例外
我有一门课是这样的:C# 模型绑定到列表抛出“;“收藏是只读的”;例外,c#,asp.net-mvc-4,razor,C#,Asp.net Mvc 4,Razor,我有一门课是这样的: public class SomeModel { public List<Item> Items { get; set; } public SomeModel() { this.Items = new List<Item>(); } } 但是,在提交后,我出现以下错误: System.NotSupportedException: Collection is read-only. 呈现的语法基本上
public class SomeModel
{
public List<Item> Items { get; set; }
public SomeModel()
{
this.Items = new List<Item>();
}
}
但是,在提交后,我出现以下错误:
System.NotSupportedException: Collection is read-only.
呈现的语法基本上与我使用@Html.HiddenFor(model=>model.Items[I].Id)
得到的语法相同,而model.Items
是一个数组而不是一个列表,这很好。这里出了什么问题
动作方法签名:
public ActionResult Post(SomeModel m)
{
我不知道为什么数组以前可以工作,但显然,这是导致问题的原因——而不是列表。当我将该数组更改为列表时,我不再收到错误。应该提到,我的模型中仍然有数组,对不起。您的数组可能正在处理Insert(创建新对象的位置) 当您尝试更新模型时,会出现此问题 对我来说,将
string[]
替换为List
解决了这个问题
//instead of....
public string[] TagsArray { get; set; }
//I now have
public List<string> TagsArray { get; set; }
//而不是。。。。
公共字符串[]TagsArray{get;set;}
//我现在有
公共列表标记数组{get;set;}
如果列表是用IList list=new list(stringArray)创建的
其中stringArray
的类型为string[]
,则无法追加它,因为它实际上是一个空间有限的数组。如果使用IList list=new list()编码>然后使用foreach
将数组的每个元素转移到列表中,然后它将能够扩展。MVC Model Binder应该与数组一起使用,因此用列表替换是一种变通方法,但不是正确的解决方案
我也有同样的问题,但这只是偶尔发生在我身上。所以我不明白为什么会发生这个问题。然后我发现了一些我认为很难分享的东西:问题出在javascript代码中
下面是我的场景:
我有一个使用一个数组的模型
public class SomeModel
{
public Item[] Items { get; set; }
public SomeModel()
{
this.Items = new Item[3] {0, 0, 0};
}
}
我发现解决方案只是改变了我用来调用web方法的javascript
->案例A-引发异常“集合为只读”
->案例B-它毫无例外地工作强>
$.ajax({
type: "POST",
async: true,
url: myUrl,
data: myData,
dataType: "html"
})
实际上MVC模型绑定应该与数组一起使用,所以用列表替换并不是我想要的答案
很好的编码。你能显示动作方法签名吗?你在哪一行得到错误?@Shyju在SomeModel()
构造函数被激发出来后的一段时间(就在它到达Post
之前)。将你的动作方法显示为well@Shyju是[HttpGet]
还是[HttpPost]
一个?在它出错之前,它永远不会到达action方法。是否有一些文档支持这背后的原因?
$.ajax({
type: "POST",
async: true,
url: myUrl,
data: JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
dataType: "html"
})
$.ajax({
type: "POST",
async: true,
url: myUrl,
data: myData,
dataType: "html"
})