ASP.Net MVC6 syntax for multiple flag form

I am creating an ASP.NET MVC6 web application (ASP.net Core 1.0) and want a simple form that contains several checkboxes for a single property, allowing several options. Say, for the sake of argument, I want the user to be able to check one or more flags from the list of colors (red, blue, green, yellow, etc.).

I have three questions related to this ...

1) What data type should the Colors property have in my view model ( string , string[] , bool[] , List<String> , something else)? SelectList still a valid thing in MVC6?

3) What is the correct syntax in my view for presenting a list of checkboxes in a form? Should I use the new helper tag here?

4) What should be the input parameters for my action with the controller? In asp.net 4.x it will be a FormCollection , but not sure if this is still relevant?

+5
source share
1 answer

I just implemented something very similar:

Flag model

 public class CheckboxModel { public int Value { get; set; } public string Text { get; set; } public bool Checked { get; set; } } 

ViewModel

 public class MyViewModel { public MyViewModel() { // populate checkbox collection with defaults here (or in your controller) } [AtLeastOneRequired(ErrorMessage = "Please check at least one checkbox.")] public class List<CheckboxModel> Checkboxes { get; set; } } 

View

 @for (var i = 0; i < Model.Checkboxes.Count; i++) { <div class="checkbox-inline"> <input type="checkbox" asp-for="@Model.Checkboxes[i].Checked"/> <input type="hidden" asp-for="@Model.Checkboxes[i].Text" /> <input type="hidden" asp-for="@Model.Checkboxes[i].Value" /> <label asp-for="@Model.Checkboxes[i].Checked">@Model.Checkboxes[i].Text</label> </div> } 

I would really like to know if there is a way to show some of this in MVC6, but I haven't found it yet.

Validation Custom Attribute

 public class AtLeastOneRequiredAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext context) { var vm = (MyViewModel) context.ObjectInstance; if (vm.Checkboxes.Any(v => v.Checked)) { return ValidationResult.Success; } return new ValidationResult(ErrorMessage); } } 

The action of the controller is simple:

 public async Task<IActionResult> MyControllerAction(MyViewModel vm) 

I know this is an old question, but hopefully this answer helps someone else.

+1
source

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


All Articles