mvc中的复选框值

时间:2012-08-23 20:25:29

标签: c# asp.net-mvc razor

我正在尝试计算如何正确表示值,选择处理以及稍后编辑表单显示选中的项目为已选中,其他可能的值为未选中。

我已经尝试了一些东西,但我不确定我是否在正确的轨道上。使用这些解决方案编辑表单只显示选中的项目,而不显示其他未检查的项目。

如果你有更好的解决方案请分享,因为我正在试图弄清楚这些是如何工作的。

这里是:假设有可能属于一个或多个角色的用户。所以我将通过两个视图模型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)

最后在Create视图中我显示这些内容 @model Models.UserViewModel

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

1 个答案:

答案 0 :(得分:0)

以下是如何操作:

<强> UserViewModel

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

<强>的FormView

您需要循环应用程序中存在的所有角色。然后,创建一个将链接到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.RolesIds中选择已由用户检查过的ID。然后,保存更改!