Asp.net mvc asp.net mvc中布尔值的Html帮助程序

Asp.net mvc asp.net mvc中布尔值的Html帮助程序,asp.net-mvc,html-helper,Asp.net Mvc,Html Helper,是否有html帮助程序方法用于在下拉列表中显示布尔值?为什么不使用html.CheckBox?为什么不使用html.CheckBox?使用下拉列表作为帮助程序。传入布尔值和包含要映射回布尔值的值的选择列表 Model.MyBooleanList可能是一个selectlist,其中包含selectlistitems{Yes,true;No,false} Model.MyBoolean只是您希望在视图中获得/设置的布尔值 <%= Html.DropDownListFor(m => m.M

是否有html帮助程序方法用于在下拉列表中显示布尔值?

为什么不使用html.CheckBox?

为什么不使用html.CheckBox?

使用下拉列表作为帮助程序。传入布尔值和包含要映射回布尔值的值的选择列表

Model.MyBooleanList可能是一个selectlist,其中包含selectlistitems{Yes,true;No,false} Model.MyBoolean只是您希望在视图中获得/设置的布尔值

<%= Html.DropDownListFor(m => m.MyBoolean, Model.MyBooleanList)%>

hth

使用dropdownlistforhelper。传入布尔值和包含要映射回布尔值的值的选择列表

Model.MyBooleanList可能是一个selectlist,其中包含selectlistitems{Yes,true;No,false} Model.MyBoolean只是您希望在视图中获得/设置的布尔值

<%= Html.DropDownListFor(m => m.MyBoolean, Model.MyBooleanList)%>

hth

这是一个旧线程,但仍处于某些搜索的顶部

您可以使用内置的DropDownListFor HTML帮助器来完成此操作:

 <%= Html.DropDownListFor(model => Model.MyBooleanProperty,new List<SelectListItem>(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%>
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return BooleanDropdownListFor(htmlHelper, expression, null);

    }
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string EmptyText)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        bool? value = null;

        if (metadata != null && metadata.Model != null)
        {
            if (metadata.Model is bool)
                value = (bool)metadata.Model;
            else if (metadata.Model.GetType() == typeof(bool?))
                value = (bool?)metadata.Model;
        }

        List<SelectListItem> items = EmptyText != null ?
            new List<SelectListItem>() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } } :
            new List<SelectListItem>() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } };

        return htmlHelper.DropDownListFor(expression, items);
    }
您还可以实现自己的HTML帮助程序:

 <%= Html.DropDownListFor(model => Model.MyBooleanProperty,new List<SelectListItem>(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%>
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return BooleanDropdownListFor(htmlHelper, expression, null);

    }
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string EmptyText)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        bool? value = null;

        if (metadata != null && metadata.Model != null)
        {
            if (metadata.Model is bool)
                value = (bool)metadata.Model;
            else if (metadata.Model.GetType() == typeof(bool?))
                value = (bool?)metadata.Model;
        }

        List<SelectListItem> items = EmptyText != null ?
            new List<SelectListItem>() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } } :
            new List<SelectListItem>() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } };

        return htmlHelper.DropDownListFor(expression, items);
    }

我建议在视图模型上使用可为null的bool属性,这样下拉列表就不会默认为false或true。您可以轻松地使用所需属性标记viewmodel,如果未选择任何选项,该属性将进行处理。

这是一个旧线程,但仍位于某些搜索的顶部

您可以使用内置的DropDownListFor HTML帮助器来完成此操作:

 <%= Html.DropDownListFor(model => Model.MyBooleanProperty,new List<SelectListItem>(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%>
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return BooleanDropdownListFor(htmlHelper, expression, null);

    }
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string EmptyText)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        bool? value = null;

        if (metadata != null && metadata.Model != null)
        {
            if (metadata.Model is bool)
                value = (bool)metadata.Model;
            else if (metadata.Model.GetType() == typeof(bool?))
                value = (bool?)metadata.Model;
        }

        List<SelectListItem> items = EmptyText != null ?
            new List<SelectListItem>() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } } :
            new List<SelectListItem>() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } };

        return htmlHelper.DropDownListFor(expression, items);
    }
您还可以实现自己的HTML帮助程序:

 <%= Html.DropDownListFor(model => Model.MyBooleanProperty,new List<SelectListItem>(){ new SelectListItem(){ Text = "Yes", Value="True"}, new SelectListItem(){ Text = "No", Value="False"}})%>
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return BooleanDropdownListFor(htmlHelper, expression, null);

    }
    public static MvcHtmlString BooleanDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, string EmptyText)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        bool? value = null;

        if (metadata != null && metadata.Model != null)
        {
            if (metadata.Model is bool)
                value = (bool)metadata.Model;
            else if (metadata.Model.GetType() == typeof(bool?))
                value = (bool?)metadata.Model;
        }

        List<SelectListItem> items = EmptyText != null ?
            new List<SelectListItem>() { new SelectListItem() { Text = EmptyText, Value = "" }, new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } } :
            new List<SelectListItem>() {new SelectListItem() { Text = "Yes", Value = "True", Selected = (value.HasValue && value.Value == true) }, new SelectListItem() { Text = "No", Value = "False", Selected = (value.HasValue && value.Value == false) } };

        return htmlHelper.DropDownListFor(expression, items);
    }
我建议在视图模型上使用可为null的bool属性,这样下拉列表就不会默认为false或true。您可以轻松地使用所需的属性标记viewmodel,如果未选择任何选项,该属性将进行处理。

我有以下内容:

public static class BoolUtility
{
    public static IEnumerable<SelectListItem> SelectList(string defaultText = null, string defaultTrue = "True", string defaultFalse = "False")
    {
        var list = new List<SelectListItem>
        {
            new SelectListItem {Text = defaultTrue, Value = "True"},
            new SelectListItem {Text = defaultFalse, Value = "False"}
        };

        if (defaultText != null)
        {
            list.Insert(0, new SelectListItem
            {
                Text = defaultText,
                Value = string.Empty
            });
        }

        return list;
    }
}
而且似乎效果很好。非常灵活,因为您可以控制所有标签,以及是否有“默认”值

哦,还有一些NUnit单元测试,如果你愿意的话。一点也不全面,但这并不复杂

[TestFixture]
class BoolUtilityTests
{
    [Test]
    public void Parameterless()
    {
        var actual = BoolUtility.SelectList().ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("True"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("False"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void LabelOverrides()
    {
        var actual = BoolUtility.SelectList(defaultTrue: "Yes", defaultFalse: "No").ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("Yes"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("No"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void IncludeDefaultOption()
    {
        var actual = BoolUtility.SelectList(defaultText: "all").ToList();
        Assert.That(actual.Count, Is.EqualTo(3));
        Assert.That(actual.First().Text, Is.EqualTo("all"));
        Assert.That(actual.First().Value, Is.EqualTo(string.Empty));
    }
}
我有这个:

public static class BoolUtility
{
    public static IEnumerable<SelectListItem> SelectList(string defaultText = null, string defaultTrue = "True", string defaultFalse = "False")
    {
        var list = new List<SelectListItem>
        {
            new SelectListItem {Text = defaultTrue, Value = "True"},
            new SelectListItem {Text = defaultFalse, Value = "False"}
        };

        if (defaultText != null)
        {
            list.Insert(0, new SelectListItem
            {
                Text = defaultText,
                Value = string.Empty
            });
        }

        return list;
    }
}
而且似乎效果很好。非常灵活,因为您可以控制所有标签,以及是否有“默认”值

哦,还有一些NUnit单元测试,如果你愿意的话。一点也不全面,但这并不复杂

[TestFixture]
class BoolUtilityTests
{
    [Test]
    public void Parameterless()
    {
        var actual = BoolUtility.SelectList().ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("True"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("False"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void LabelOverrides()
    {
        var actual = BoolUtility.SelectList(defaultTrue: "Yes", defaultFalse: "No").ToList();
        Assert.That(actual.Count, Is.EqualTo(2));
        Assert.That(actual.First().Text, Is.EqualTo("Yes"));
        Assert.That(actual.First().Value, Is.EqualTo("True"));
        Assert.That(actual.Last().Text, Is.EqualTo("No"));
        Assert.That(actual.Last().Value, Is.EqualTo("False"));
    }

    [Test]
    public void IncludeDefaultOption()
    {
        var actual = BoolUtility.SelectList(defaultText: "all").ToList();
        Assert.That(actual.Count, Is.EqualTo(3));
        Assert.That(actual.First().Text, Is.EqualTo("all"));
        Assert.That(actual.First().Value, Is.EqualTo(string.Empty));
    }
}

如果你想获取YES,NO和NOTSET NO答案的值,我建议你使用这样的下拉列表

Public Class MyModelClass
{
  [Display(Name = "Project Based Subsidy?")]
  public Nullable<bool> IsSubsidyProjectBased{ get; set; }

  public SelectList DropDownItems
  {
      get
      {
          List<DropDownItems> ddItem = new List<DropDownItems>();
          ddItem.Add(new DropDownItems("--Select--", null));
          ddItem.Add(new DropDownItems("Yes", true));
          ddItem.Add(new DropDownItems("No", false));                
          return new SelectList(ddItem, "Value", "Text");
      }
  }

public class DropDownItems
{
    public DropDownItems(string text, bool? value)
    {
        this.Text = text;
        this.Value = value;
    }
    public string Text { get; set; }
    public bool? Value { get; set; } 
}

}

如果你想获取YES,NO和NOTSET NO答案的值,我建议你使用这样的下拉列表

Public Class MyModelClass
{
  [Display(Name = "Project Based Subsidy?")]
  public Nullable<bool> IsSubsidyProjectBased{ get; set; }

  public SelectList DropDownItems
  {
      get
      {
          List<DropDownItems> ddItem = new List<DropDownItems>();
          ddItem.Add(new DropDownItems("--Select--", null));
          ddItem.Add(new DropDownItems("Yes", true));
          ddItem.Add(new DropDownItems("No", false));                
          return new SelectList(ddItem, "Value", "Text");
      }
  }

public class DropDownItems
{
    public DropDownItems(string text, bool? value)
    {
        this.Text = text;
        this.Value = value;
    }
    public string Text { get; set; }
    public bool? Value { get; set; } 
}

}

从技术上讲,不能使用复选框生成空值。如果情况的语义需要一个我不知道的可能性,那么您需要另一个方法。但除此之外,这是正确的选择。或者可能是Html.CheckBoxx=>x.Property.@NickLarsen,虽然我同意,但OP特别询问bools。除非没有声明它可以为null,否则这不是问题。从技术上讲,您不能使用复选框生成null值。如果情况的语义需要一个我不知道的可能性,那么您需要另一个方法。但除此之外,这是正确的选择。或者可能是Html.CheckBoxx=>x.Property.@NickLarsen,虽然我同意,但OP特别询问bools。除非没有声明它是可空的,否则这不是问题。你期望什么html?带有选项项的select元素,选项项的值为true或false?您希望使用什么html?具有选项项且值为true或false的select元素?