Lately, I've been working on enabling more of the Visual Studio code analysis rules in my projects. However, I keep bumping into rule CA2227: "Collection properties should be read only".
Say I have a model class like this:
public class Foo
{
public string Name { get; set; }
public List<string> Values { get; set; }
}
And I have a strongly-mapped view page:
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Name)
@Html.EditorFor(m => m.Name)
for (int i = 0; i < Model.Values.Count; i++)
{
<br />
@Html.LabelFor(m => Model.Values[i]);
@Html.EditorFor(m => Model.Values[i]);
}
<button type="submit">Submit</button>
}
With ASP.NET MVC, I can write an action in my controller that will automatically bind this input to a class of type Foo
:
[HttpPost]
public ActionResult ProcessForm(Foo model)
{
return View(model);
}
The problem with this approach, is that my List<string>
auto property violates rule CA2227. If I wasn't doing model binding, I could make the property read only and populate the collection elsewhere. However, that approach won't work with the default model binder. For now I've just been adding a suppression message when it occurs in a view model.
Is there a way I can bind a collection of items in a model without violating CA2227? Or is adding a suppression message my best option here?
I believe you would need to create a custom ModelBinder
to work around this, which isn't worth it. In this case since there's reasonable benefit to break the rule go ahead and suppress it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With