本文介绍了设置CheckBox的Checked属性在ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绕开缺乏在ASP.NET MVC中一个的CheckBoxList的。我已经得到的地步,我可以呈现枚举值的列表就好了,但我卡在如何根据我的模型设定选中属性 - 在这种情况下是有作用的实体一个IList用户实体。角色ID的对应枚举值。

这个例子是使用Spark视图引擎的语法,但它的功能上等同于标准的ASP.NET MVC视图引擎($(是一样的<%=或<%)

 <用于每个=在Enum.GetValues​​变种R(typeof运算(的UserRole))>
    <标签><输入类型=复选框NAME =角色值=$ {(INT)R}签=[如何最哎呀到I-GET-这个?]/&GT ; $ {R}< /标签>
< /为>


解决方案

如果您的角色是这样定义的,那么你可以将多个角色与用户关联

  [国旗]
公共枚举的UserRole
{
    的DataReader = 1,
    ProjectManager = 2,
    管理员= 4,
}

通过添加一个简单的扩展方法,你可以检查,如果你的角色包含一个目标的作用

 公共静态类RoleExtension
{
    公共静态布尔HasRole(这UserRole的targetVal,UserRole的checkVal)
    {
        返回((targetVal&安培; checkVal)== checkVal);
    }
}

在您查看更新的复选框,不知道下面是您视图引擎的正确方法使用扩展方法。

 <用于每个=在Enum.GetValues​​变种R(typeof运算(的UserRole))>
<标签>
    <输入
       类型=复选框
       NAME =角色
       值=$ {(INT)R}
       检查=$ {?Model.Role.HasRole(R)选中:}的String.Empty/>
< /标签>

I'm trying to work around the lack of a CheckBoxList in ASP.NET MVC. I've gotten to the point I can render a list of Enum values just fine, but I'm stuck on how to set the checked attribute based on my Model - Which in this case is a User entity that has an IList of Role entities. The role id's correspond to the enum values.

This example is using the Spark View Engine syntax, but it's functionally identical to the standard ASP.NET MVC view engine ("$(" is the same as "<%=" 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>
解决方案

If your roles are defined like this then you can associate more than one role with the user

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

By adding a simple extension method you can check if you role contains a target role

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

Use the extension method in you view to update the check box, not sure if the following is the correct way for your view engine.

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

这篇关于设置CheckBox的Checked属性在ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 22:42
查看更多