Problem:
I want to display a list of checkboxes based on enums: e.g. item1[] item2[] item3[]
However these checkboxes need to be checked based on the contents of a comma seperated list model.platforms
For example:
If model.platforms = "1,3,5", then the output on the page should be:
item1[x] item2[] item3[x] item4[] item5[x]
What I have done so far:
So far I have tried creating a custom helper which takes in the enum type and my "model.platforms. The aim is to split the platforms at the comma and then when iterating through the enums, check the checkbox if the value for the enum is in the list.
Am I even approaching this right? I know my way around MVC/C# but these helpers really are new to me. Any guidance to point me in the right direction would be appreciated
I have tried to look up various solutions on S.O, but most of them revolve around the enums being part of the model which isn't practical for me due to the way the model is generated(and I really don't want to add a view model for this particular scenario)
Code so far
--helper.cs--
public static MvcHtmlString PlatformList<enumType>(this HtmlHelper htmlHelper, string platformList)
{
List<string> selectedPlatforms = platformList.Split('/').ToList(); //This will come from model.platforms ("platform1/platform2/etc")
TagBuilder tg = new TagBuilder("div");
string innerhtml = "";
foreach (var item in Enum.GetValues(typeof(enumType)))
{
innerhtml = innerhtml + "{build up here}";
}
tg.SetInnerText(innerhtml);
return new MvcHtmlString(innerhtml);
}
--Enum.cs--
public enum en_GamePlatforms
{
[Display(Name = "PC")]
PC =1,
[Display(Name = "DOS")]
DOS = 2,
...{etc}...
}
--View--
@(Html.Raw(Html.PlatformList<MagpieEnumerations.en_GamePlatforms>(Model.Platform).ToString()))
Below is my original approach which i really don't like, but provides the correct output on the page.(but does it off enum name rather than value :())
@{
List<string> platformsActive = Model.Platform.Split(',').ToList();
}
@foreach (myenums.en_GamePlatforms item in Enum.GetValues(typeof(myenums.en_GamePlatforms)))
{
<span>
@Html.Label("SelectedPlatform" + item, Enum.GetName(typeof(myenums.en_GamePlatforms), item))
@{bool t = platformsActive.Contains(item.ToString(Model));}
<input name="Selectedtypes" id="Selectedtypes" type="checkbox" @(t ? "checked='checked'" : "") value="@item"/> |
</span>
}