【问题标题】:asp.net core mvc tag helper for bootstrap toggle用于引导切换的 asp.net 核心 mvc 标签助手
【发布时间】:2018-06-11 06:42:40
【问题描述】:

我目前正在编写一个 asp.net core mvc 应用程序,并且我是 .net core 的新手。我对标签助手感到兴奋,我正试图用我的大脑围绕它们。我得到并制作了一对简单的,但我真正需要的是用bootstrap toggle替换<input type="checkbox">

我已经能够使用我的自定义“布尔”标签助手来显示切换工作

    <div class="form-group">
        <label asp-for="IsBusiness"></label>
        <boolean asp-for="IsBusiness" class="form-control"/>
        <span asp-validation-for="IsBusiness" class="text-danger"></span>
    </div>

但是我遇到的问题是当用户打开复选框/切换按钮然后单击保存时保存它的值。我收到一个错误:"The value 'on' is not valid for Login Is A Business?." 在表单验证中。

谁能帮我解决这个问题,这需要隐藏字段吗?

到目前为止,这是我的标签助手:

using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Bidz4Hire.Utility.TagHelpers
{
    // Creates <input type="checkbox" data-toggle="toggle" />
    [HtmlTargetElement("boolean")]
    public class BooleanTagHelper : InputTagHelper
    {

        public BooleanTagHelper(IHtmlGenerator generator) : base(generator)
        {
        }

        public string AspFor { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
        output.TagName = "input";
        output.TagMode = TagMode.SelfClosing;

        output.Attributes.SetAttribute("type", "checkbox");
        output.Attributes.SetAttribute("id", For.Name);
        output.Attributes.SetAttribute("name", For.Name);
        output.Attributes.SetAttribute("data-toggle", "toggle");
        output.Attributes.SetAttribute("data-on", "Yes");
        output.Attributes.SetAttribute("data-off", "No");
        output.Attributes.SetAttribute("value", "true");  //so the checked value returned is "true" not "on"
        if (Convert.ToBoolean(For.Model) == true) //check the model value
        {
            output.Attributes.SetAttribute("checked", "checked"); //turns the toggle to "Yes" initially
        }
    }
}

【问题讨论】:

    标签: jquery asp.net twitter-bootstrap asp.net-core-tag-helpers


    【解决方案1】:

    好吧,经过几个小时的尝试不同的事情和搜索互联网,我终于弄明白了。我已将上面的代码编辑为工作版本。

    基本上你需要做两件事:

    1. 将属性“值”设置为“true”,因此在选中复选框时(切换设置为“是”)返回的值是“true”而不是“开”,这是复选框的默认值。李>
    2. 检查模型属性,如果为真则为“checked”添加一个属性。

    我在原始帖子中用 cmets 突出显示了两者。

    我希望这对其他人有所帮助,因为我浪费了很多时间来解决这个问题。在现代网络应用程序中,切换看起来比复选框好得多,因此恕我直言,这是非常值得的。

    【讨论】:

      【解决方案2】:

      感谢您的解决方案,只是想指出要使用此解决方案,您必须将 dll 添加到 _ViewImports.cshtml 文件中。

      @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
      @addTagHelper *, DLLOfCustomHelper
      

      我没有足够的代表来评论你的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-08
        • 2019-11-13
        • 2019-02-17
        • 2021-11-27
        • 2020-05-16
        • 2017-05-14
        • 2019-09-10
        • 1970-01-01
        相关资源
        最近更新 更多