Read-only collection in array in ViewModel

I have an MVC ViewModel that looks like this:

public class FruitBoxViewModel {

    public FruitBoxViewModel()
    {
        BoxLabels = new BoxLabelViewModel[3];
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public BoxLabelViewModel[] BoxLabels {get; set; }
}

      

A commented request to see what it looks like BoxLabelViewModel

, here it is:

public class BoxLabelViewModel {
    public string SkuCode {get; set;}
    public int? ProductionNumber { get; set; }
}

      

Everyone FruitBox

can have from 1 to 3 BoxLabels

, no more, no less. To enforce this, I decided to use Array

instead List

.

I have a for loop in a Razor view that processes my inputs on a page:

@for(var i = 0; i < 3; i++ )
{
  @Html.LabelFor(model => Model.BoxLabels[i].SkuCode)
  @Html.EditorFor(m => Model.BoxLabels[i].SkuCode, new { htmlAttributes = new { @class = "form-control" } })
}

      

When I submit the form, I get a yellow screen of death (YSOD) with the error:

The collection is read-only.

Description: An unhandled exception was thrown during the execution of the current web request. Review the stack trace for more information about the error and how it occurs in your code.

Exception Details: System.NotSupportedException: The assembly is read-only.

Is there a rule that I'm not aware of that says you should never use Array in ViewModels or something?

+3


source to share


1 answer


This is one of the cases where you used an array instead of a list. The model binder will not create a new array instance because you provided it in the constructor. It will then use it as an instance IList

and try to call Insert

or Add

, and such calls will fail for an array and succeed for a list.



Just remove the assignment form constructor or use a list in your model and write some JS to validate your form before submitting the post request. Then check the cardinality on the server side.

+3


source







All Articles