asp.net-mvc 使用 CheckBoxFor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4804132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:47:56  来源:igfitidea点击:

using CheckBoxFor

asp.net-mvcasp.net-mvc-3

提问by learning

I am having a class Role as follows;

我有一个类角色如下;

public enum Role
{                                            
    User1 = 1,
    User2 = 2,
    User3 = 3, 
    User4 = 4
}

I have the following codes in my model

我的模型中有以下代码

public Role[] UserRoles { get; set; }
 User user = User.Load(1);
        UserRoles = user.Roles;

My question is as follows: I want to have a checkbox for each Role and if Role == userRoles, the checkbox is true else false. How can I use @HTml.CheckboxFor...Can I have an example please.

我的问题如下:我想为每个角色设置一个复选框,如果角色 == userRoles,则该复选框为真,否则为假。我如何使用@HTml.CheckboxFor...我可以举个例子吗?

采纳答案by Rob

You're going to come unstuck with hard-coded values if you are trying to create a checkbox list based on data from a DB.

如果您尝试根据数据库中的数据创建复选框列表,您将无法使用硬编码值。

You could try something like my CheckBoxListFor<> Extension:

你可以尝试像我的 CheckBoxListFor<> 扩展:

How to create a CheckBoxListFor extension method in ASP.NET MVC?

如何在 ASP.NET MVC 中创建 CheckBoxListFor 扩展方法?

回答by Omu

to use the CheckBoxFor you need a ViewModel with bool properties

要使用 CheckBoxFor 你需要一个带有 bool 属性的 ViewModel

public class YourVM
{                                            
  public bool[] Roles {get;set;}
}

and in the view

并且在视图中

@model YourVM

@for (int i = 0; i < Model.Roles.Count(); i++) {
@Html.CheckBoxFor(m => m.Roles[i])
}

回答by Nick Larsen

I answered this and your other question, on your other question. There is no reason to make multiple questions for the same problem, you can edit your own questions.

我在你的另一个问题上回答了这个和你的另一个问题。没有理由为同一个问题提出多个问题,您可以编辑自己的问题。

Difficulty in filling list while comparing arrays

比较数组时难以填充列表