【问题标题】:How to add additional attribute for dynamic object?如何为动态对象添加附加属性?
【发布时间】:2016-07-31 12:47:24
【问题描述】:

如果 FlagAccessEdit =false,如何禁用或只读?

public static MvcHtmlString CCheckBox(this HtmlHelper htmlHelper,
字符串名称,对象 htmlAttributes,
bool FlagAccessEdit = true, bool FlagAccessView = true)
{

            如果 (!FlagAccessView)
                返回 MvcHtmlString.Empty;
            else if (!FlagAccessEdit && FlagAccessView)
            {
                返回 htmlHelper.CheckBox(name, htmlAttributes);
            }
            别的
                返回 htmlHelper.CheckBox(name, htmlAttributes);
}

【问题讨论】:

  • 如何使禁用或只读 id FlagAccessEdit =false?
  • 如果此评论是问题的一部分,您应该将其编辑到问题中,而不是作为评论。
  • Ashish Shukla 的回答显示了一种解决方案,但重点是什么。没有只读复选框之类的东西,禁用它意味着您总是回发false,即使该复选框最初显示为选中(true),这无疑会搞砸您的应用程序。如果你想这样做,为某个文本的值生成一个隐藏的输入(比如“是”或“否”)

标签: asp.net-mvc c#-4.0


【解决方案1】:

您需要获取现有的 htmlAttribute 并根据您的条件添加禁用或只读。下面是正确的代码

辅助方法

public static MvcHtmlString CCheckBox(this HtmlHelper htmlHelper,
        string name, object htmlAttributes,bool FlagAccessEdit = true, 
        bool FlagAccessView = true)
    {
        //get the htmlAttribute
        IDictionary<string, object> attributes = new RouteValueDictionary(htmlAttributes);

        if (!FlagAccessView)
            return MvcHtmlString.Empty;
        else if (!FlagAccessEdit && FlagAccessView)
        {
            //Add the disabled attribute
            attributes.Add("disabled", "disabled");
            return htmlHelper.CheckBox(name, attributes);
        }
        else
        {
            return htmlHelper.CheckBox(name, htmlAttributes);
        }

    }

如下调用方法

@Html.CCheckBox("chkCheckbox", new { id="chkDemo"},false,true)

【讨论】:

  • 非常感谢 Ashish。它按预期工作正常 :)
猜你喜欢
  • 2022-09-27
  • 2021-03-19
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2021-07-14
  • 2014-05-29
  • 2012-01-12
相关资源
最近更新 更多