如何在asp.net-mvc中的html文本框上设置禁用属性?

问题描述 投票:0回答:3

我正在尝试动态设置 html 文本框上的禁用属性并遇到问题

我在我看来尝试过这个:

 string disabledString = "";
 if (SomeLogic)
 {
      disabledString = "disabled";
 }

 Html.Textbox()...new Dictionary<string, object> { { "maxlength", 50 }, { "disabled", readOnlyState } })%>

如您所见,我将禁用属性设置为“”或禁用,但当我测试时,在任何一种情况下它似乎都被禁用。 我是不是错过了什么?

html asp.net-mvc textbox
3个回答
17
投票

这对我们来说很难看,因为这里的 HTML 规范很糟糕。

基本上,在我们的视图代码中,我们有一些这样的逻辑:

bool isPlatformOwner = false;

object disabledAttributes = new { @disabled="disabled", @readonly="readonly" };

//omitted code setting isPlatformOwner    

    if (isPlatformOwner)
    {
        disabledAttributes = new { };
    }

然后,对于我们的控件,我们有这样的:

<%=Html.CheckBoxFor(f => f.AddToReleaseIndicator, disabledAttributes)%>

匿名类型拯救了我们,但是,就像我说的,它变得有点难看。


3
投票

实际上,可以向

HtmlHelper
编写一个扩展类来执行此操作,但是您必须实现许多覆盖,因此我发现的最快解决方案是编写一个字典扩展。

您可以使用以下课程:

public static class DictionaryExtensions
{
    public static Dictionary<string, object> WithAttrIf(this Dictionary<string,object> dictionary,bool condition, string attrname, object value)
    {
        if (condition)
            dictionary[attrname] = value;

        return dictionary;
    }

    public static Dictionary<string, object> WithAttr(this Dictionary<string, object> dictionary, string attrname, object value)
    {
        
        dictionary[attrname] = value;

        return dictionary;
    }
}

要使用它,请在视图中导入该类,您的视图代码如下所示:

@Html.TextBoxFor(m => m.FirstName, new Dictionary<string, object>().WithAttr("class","input-large").WithAttrIf(!string.IsNullOrWhiteSpace(Model.FirstName),"readonly","yes"))

您可以添加任意数量的属性,因为扩展方法会将值添加到字典中并返回字典本身。


1
投票

我认为当您希望启用禁用属性时,您希望完全忽略它。较旧的浏览器会查看以下内容并禁用文本框:

<input type="text" disabled></input>

换句话说,在旧的 HTML 中,“disabled”不是必需的,因此出于兼容性原因,如果您希望它正确呈现,您应该忽略该属性。不过,我不确定如果您尝试严格的 DOCTYPE 会发生什么。

© www.soinside.com 2019 - 2024. All rights reserved.