CA2227 and ASP.NET Model Binding

Recently, I have been working to include more Visual Studio code analysis rules in my projects. However, I continue to encounter rule CA2227 : "Collection properties should only be read."

Say I have a model class as follows:

public class Foo { public string Name { get; set; } public List<string> Values { get; set; } } 

And I have a highly displayed browse 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 the class type Foo :

 [HttpPost] public ActionResult ProcessForm(Foo model) { return View(model); } 

The problem with this approach is that my List<string> auto property violates CA2227 rule. If I did not bind to the model, I could make the property read-only and populate the collection elsewhere. However, this approach will not work with the default model binding. For the moment, I'm just adding a suppression message when it appears in the view model.

Is there a way to bind a collection of elements in a model without breaking CA2227? Or adds a message about suppressing my best option here?

+4
source share
1 answer

I believe that you need to create a custom ModelBinder to get around this, which is not worth it. In this case, since the reasonable benefits of breaking the rule go ahead and suppress it.

+3
source

Source: https://habr.com/ru/post/1499844/


All Articles