我试图阻止用户在某些情况下使用输入,但如果我向其添加disabled,则无论其值是true还是false,都将禁用输入.

这是我的代码:

@Html.TextBoxFor(model => model.inputName, new { @disabled = (condition ? "true" : "false") })

在任何情况下,它都将被禁用.

推荐答案

因为是否禁用取决于disabled属性而不是disabled属性值

下面是一个例子

<p>Last name: <input type="text" name="lname" disabled="" /></p>
<p>Last name: <input type="text" name="lname" disabled="true" /></p>
<p>Last name: <input type="text" name="lname" disabled="false" /></p>

如果你不想用Js来控制你的属性,我们可以判断if条件为真,以创建disabled的元素,否则就不是了.

@if(condition) 
{
    Html.TextBoxFor(model => model.inputName, new { @disabled = "true" })
}
else
{
    Html.TextBoxFor(model => model.inputName)
}

否则我们可以为此创建一个扩展方法.

public static class TextBoxForExtensions
{
    public static IHtmlString TextBoxFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        object htmlAttributes, 
        bool disabled
    )
    {
        var attributes = new RouteValueDictionary(htmlAttributes);
        if (disabled)
        {
            attributes["disabled"] = "disabled";
        }
        return htmlHelper.TextBoxFor(expression, attributes);
    }
}

然后我们可以使用

@Html.TextBoxFor(model => model.inputName, new{},condition)

Csharp相关问答推荐

有没有一种方法可以防止在编译时在MicrosoftC或非单线程上下文中调用方法?

try 还原包时出错:Dapper已经为System.Data.SQLClient定义了依赖项''''

通过条件列表删除/更新EF Core 7中的实体的有效方法

在发布表单时绑定包含附加(嵌套)列表的对象列表的正确语法是什么

为什么总输出就像12.3没有一分一样?

将XPS转换为PDF C#

图形API基于appid列表检索多个应用程序

使页面内容居中

使用HttpResponseMessage中的嵌套列表初始化JSON

Rx.Net窗口内部可观测数据提前完成

自定义列表按字符串的部分排序

具有类型识别的泛型方法

在使用UserManager时,如何包含与其他实体的关系?

我什么时候应该在Dapper中使用Connection.OpenAsync?

在C#中,当输入一个方法/局部函数时,我的IEnumerator被重置/重新创建.为什么?

RCL在毛伊岛应用程序和Blazor服务器应用程序.Net 8.0中使用页面

映射器-如何映射到多个实体

使用免费的DotNet库从Azure函数向Azure文件共享上的现有Excel文件追加行

能否将我图表中的星号与X轴上一天中的第二位数字对齐?

PowerShell:如何[引用]数组中的元素?