我试图弄清楚如何正确表示值,选择的过程以及稍后在编辑表单上将选中的项目显示为选中状态,将其他可能的值显示为未选中。

我已经尝试了一些东西,但不确定自己是否走对了。使用这些解决方案时,编辑表单仅显示选中的项目,而不显示其他未选中的项目。

如果您有更好的解决方案,请分享,因为我试图弄清楚它们是如何工作的。

在这里是:假设有一个用户可能属于一个或多个角色。因此,我将通过两个视图模型来表示这些视图模型:UserViewModel和RoleViewModel

**UserViewModel.cs**

public int id {get; set;}
public string username {get; set;}

public UserViewModel()
{
   Roles = new List<RoleViewModel>();
}

public void SendToDomain(User user, ISession nhibSession)
{
   if(user.Roles != null)
   {
      user.Roles.Clear();//Clear previous selected items
      foreach(Role role in Roles)
      {
        if(role.IsInRole)
          user.Role.Add(nhibSession.Load<Role>(user.RoleId));
      }
   }
}

**RoleViewModel**
public bool IsInRole {get; set;}

[HiddenInput(displayValue = false)]
public int RoleId {get; set;}

[HiddenInput(displayValue = true)]
public string RoleName {get; set;}


在EditorTemplates里面,我有RoleViewModel.cs

@model Models.RoleViewModel

@Html.CheckBoxFor(m=>m.IsInRole)
@Html.HiddenFor(m=>m.RoleId)
@Html.LabelFor(m=>m.IsInRole, Model.RoleName)


最后在“创建”视图中,我将这些显示为
@model Models.UserViewModel

<div> User roles </div> <div> @Html.EditorFor(m => m.Roles) </div>

最佳答案

方法如下:

UserViewModel

public int id {get; set;}
public string username {get; set;}
public int[] RoleIdsSelected { get; set; }


表格浏览

您需要循环使用应用程序中存在的所有角色。然后,创建一个将链接到您的UserViewModel.RolesIdsSelected的复选框,并将值与当前打印的role.RoleId进行比较。如果有匹配项,将进行检查。

@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中已由用户检查过的ID。然后,保存更改!

08-26 16:07