這裏是如何做到這一點:
UserViewModel
public int id {get; set;}
public string username {get; set;}
public int[] RoleIdsSelected { get; set; }
FormView控件
您需要循環存在於應用程序的所有角色。然後,創建一個複選框,該複選框將鏈接到您的UserViewModel.RolesIdsSelected,並將這些值與當前角色進行比較。如果有一場比賽,將會有一張支票。
@model UserViewModel
@{
foreach (var role in (IEnumerable<Role>)ViewBag.AllRoles)
{
<label>
@Html.CheckBoxFor(x => x.RoleIdsSelected, role.RoleId)
@role.RoleName
</label>
}
}
CheckboxExtensions
public static class InputExtensions
{
public static MvcHtmlString CheckBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value)
{
return htmlHelper.CheckBoxFor<TModel, TProperty>(expression, value, null);
}
public static MvcHtmlString CheckBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
return htmlHelper.CheckBoxFor<TModel, TProperty>(expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString CheckBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
{
ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
return CheckBoxHelper<TModel, TProperty>(htmlHelper, modelMetadata, modelMetadata.Model, ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
}
private static MvcHtmlString CheckBoxHelper<TModel, TProperty>(HtmlHelper htmlHelper, ModelMetadata metadata, object model, string name, object value, IDictionary<string, object> htmlAttributes)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
RouteValueDictionary routeValueDictionary = htmlAttributes != null ? new RouteValueDictionary(htmlAttributes) : new RouteValueDictionary();
string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (string.IsNullOrEmpty(fullHtmlFieldName))
{
throw new ArgumentException("Le nom du control doit être fourni", "name");
}
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes<string, object>(htmlAttributes);
tagBuilder.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.CheckBox));
tagBuilder.MergeAttribute("name", fullHtmlFieldName, true);
string text = Convert.ToString(value, CultureInfo.CurrentCulture);
tagBuilder.MergeAttribute("value", text);
if (metadata.Model != null)
{
foreach (var item in metadata.Model as System.Collections.IEnumerable)
{
if (Convert.ToString(item, CultureInfo.CurrentCulture).Equals(text))
{
tagBuilder.Attributes.Add("checked", "checked");
break;
}
}
}
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
}
}
當你將發佈你的數據,你將不得不在UserViewModel.RolesIdsSelected已經由用戶選擇了IDS。然後,保存更改!