Setting the CheckBox Checked Property in ASP.NET MVC

I am trying to get around the lack of CheckBoxList in ASP.NET MVC. I got to the point that I can display the list of Enum values ​​in order, but I was fixated on how to set a valid attribute based on my model. In this case, it is a user object that has an IList of Role objects. The role identifier corresponds to the enumeration values.

This example uses the Spark View Engine syntax, but it is functionally identical to the standard ASP.NET MVC viewers ("$ (" matches "<% =" or "<%")

<for each="var r in Enum.GetValues(typeof(UserRole))">
    <label><input type="checkbox" name="Roles" value="${(int)r}" checked="[How-The-Heck-To-I-Get-This?]" />${r}</label>
</for>
+3
source share
4 answers

,

[Flags]
public enum UserRole
{        
    DataReader = 1,
    ProjectManager = 2,
    Admin = 4,
}

, ,

public static class RoleExtension
{
    public static bool HasRole(this UserRole targetVal, UserRole checkVal)
    {
        return ((targetVal & checkVal) == checkVal);
    }
}

, , , .

<for each="var r in Enum.GetValues(typeof(UserRole))">
<label>
    <input 
       type="checkbox"
       name="Roles" 
       value="${(int)r}" 
       checked="${Model.Role.HasRole(r) ? "checked" : string.Empty}" />
</label>

+8
<for each="var r in Enum.GetValues(typeof(UserRole))">
    <label>
      <% if (r.Checked) { %>
        <input type="checkbox" checked="checked" />${r}
      <% } else { %>
        <input type="checkbox" />${r}
      <% } %>
    </label>
</for>

P.S. , , .

+3

"" string.Empty, .

<label>
    <input type="checkbox"
           name="Roles"
           value="${(int)r}"
           ${ Model.Role == r ? "checked='checked'" : string.Empty } />
    ${r}
</label>
+2

Hey, I really couldn't get these methods to work. Setting the value of the "checked" attribute to an empty string still leads to the checkbox in IE. My solution was to add the HtmlHelper extension:

public static string SimpleCheckbox(this HtmlHelper helper, 
                                    string name, 
                                    string value, 
                                    bool isChecked)
{
    return String.Format("<input type=\"checkbox\" name=\"{0}\" value=\"{1}\" " + (isChecked ? "checked" : "") + "/>", name, value);
}

And in the markup:

<%= Html.SimpleCheckbox("checkboxId", item.Id, item.IsSelected) %>
+1
source

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


All Articles