c# - 绑定(bind)到列表的模型抛出 "Collection is read-only"异常

标签 c# asp.net-mvc-4 razor

我有这样一个类:

public class SomeModel
{
    public List<Item> Items { get; set; }

    public SomeModel()
    {
        this.Items = new List<Item>();
    }

}

在表单发布时可以有可变数量的 Item,从零到很多。我正在使用 javascript 在提交时动态附加隐藏的输入字段:

$("#container").children(".item").each(function (i) {
    form.append('<input type="hidden" name="Items[' + i + '].Id" value="' + $(this).val() + '" />');
});

然而,提交后,我得到这个错误:

System.NotSupportedException: Collection is read-only.

呈现的语法与我使用 @Html.HiddenFor(model => model.Items[i].Id)model.Items 得到的基本相同> 是一个数组而不是一个列表,并且工作正常。这里出了什么问题?

Action 方法签名:

public ActionResult Post(SomeModel m)
{

最佳答案

您的 Array 可能正在处理 Insert(创建新对象的地方)。

当您尝试更新模型时会出现此问题。

对我来说,替换 string[]List<string>解决了问题。

//instead of....
public string[] TagsArray { get; set; }

//I now have
public List<string> TagsArray { get; set; }

关于c# - 绑定(bind)到列表的模型抛出 "Collection is read-only"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20405400/

相关文章:

c# - 我将如何在 mvc 4 中将以下语句的值设置为零

asp.net-mvc - MVC 中的流畅验证 : specify RuleSet for Client-Side validation

c# Asp.NET MVC 使用 FileStreamResult 下载 excel 文件

asp.net-mvc - @ Html.EditorFor()呈现DropDownList而不是CheckBox

javascript - 当尝试执行基于 ajax 的分页或过滤时,在部分 View 内呈现的 WebGrid 将引发 "“jQuery is not defined” "

c# - .Net 单例属性的延迟初始化

c# - 如何实现只运行一次的.net core IHostedService

C# - 数据表中的数据表

c# - 在短暂延迟后获取 aspx 页面的执行输出

c# - 具有 asp-controller 和 asp-action 属性的 anchor 不会呈现为链接