I have this class:
public class UserFilter
{
public bool IsShowCars { get; set; } = true;
public bool IsShowBikes { get; set; } = true;
public bool IsShowMotorcycles { get; set; } = true;
public bool IsShowTrucks { get; set; } = false;
public bool IsShowPlanes { get; set; } = true;
public bool IsShowTrains { get; set; } = true;
}
And I want to create a checkbox in my .cshtml view file, using CheckBoxFor and a LabelFor, for each property in the class, in order to bind them to the Model.
Is there any way of doing that with a Foreach loop, without literally typing each of them like @Html.CheckBoxFor(m => m.Filter.IsToShowCars)
?
CodePudding user response:
You can bind a IDictionary<string, bool>
in a loop to checkboxes.
public class UserFilter
{
public bool IsShowCars { get; set; } = true;
public bool IsShowBikes { get; set; } = true;
public bool IsShowMotorcycles { get; set; } = true;
public bool IsShowTrucks { get; set; } = false;
public bool IsShowPlanes { get; set; } = true;
public bool IsShowTrains { get; set; } = true;
public IDictionary<string, bool> ToCheckList()
{
// Convert your model to
// a 'loopable' collection
var json = JsonSerializer.Serialize(this);
var dict = JsonSerializer.Deserialize<IDictionary<string, bool>>(json);
return dict;
}
public static UserFilter FromCheckList(IDictionary<string, bool> dict)
{
// Convert the collection
// back to your model
// Attention: this creates a new object!
var json = JsonSerializer.Serialize(dict);
return JsonSerializer.Deserialize<UserFilter>(json);
}
}
Eventually you can change it to fill the existing properties in FromCheckList
to the current instance.