2

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>
            }
0

1 Answer 1

1

You can achieve it by using following code.

public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
{
    StringBuilder sb = new StringBuilder();

    foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
    {
        TagBuilder builder = new TagBuilder("input");
        long targetValue = Convert.ToInt64(item);
        long flagValue = Convert.ToInt64(modelItems);

        if ((targetValue & flagValue) == targetValue)
            builder.MergeAttribute("checked", "checked");

        builder.MergeAttribute("type", "checkbox");
        builder.MergeAttribute("value", item.ToString());
        builder.MergeAttribute("name", name);
        builder.InnerHtml = item.ToString();

        sb.Append(builder.ToString(TagRenderMode.Normal));
    }

    return new HtmlString(sb.ToString());
}

Please refer this url checkboxlist in asp.net MVC

Sign up to request clarification or add additional context in comments.

1 Comment

This was really useful, I used this as a template but had to take out the <T> section of the function as this type will always use a certain enum. +1 !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.