设置属性" readonly" for @ Html.TextBoxFor()动态地基于来自db的获取信息

时间:2017-11-14 19:30:34

标签: asp.net asp.net-mvc entity-framework razor html.textboxfor

我使用@ Html.TextBoxFor()定义了多个Textbox。现在我希望他们中的一些只是" readonly"根据用户访问页面的角色,其中一些是可编辑的。

我尝试使用以下

@Html.TextBoxFor(f => f.VSSLabel, new { style = "height:19px", @Value = @ViewBag.fetchf.VSSLabel, @readonly="readonly" })

有没有办法可以设置@readonly =" false"它变得可编辑,或任何其他方法,所以我把它切换到" readonly"并且可以根据存储在来自控制器的ViewBag变量中的值进行编辑?

4 个答案:

答案 0 :(得分:1)

不幸的是,以下所有标记都将呈现只读文本框输入

<input type="text" name="s1" readonly="readonly"/>
<input type="text" name="s2" readonly="no" />
<input type="text" name="s2" readonly="reallyDoNotWant" />
<input type="text" name="s3" readonly="false" />
<input type="text" name="s4" readonly />

readonly属性的存在使得输入元素只读。价值无关紧要。

所以你应该有条件地渲染它

if (yourExpressionWhichGivesBooleanValue)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}

如果要根据viewbag字典项检查

if (ViewBag.IsAdmin !=null && ViewBag.IsAdmin)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}

假设您在操作方法中将ViewBag.IsAdmin设置为布尔值。

答案 1 :(得分:1)

Shyju的说法是正确的,但是Shariq Ali是正确的,如果您有很多工作要做,那么Razor代码的效率将非常低。

就我而言,我有一个完整的表格,在某些情况下我想使其只读。我发现做到这一点的一种方法可以用更少的编码来解决您的问题。

@{
object htmlAttr = null;

if ( ViewBag.AllowEdit != null && !ViewBag.AllowEdit ){
    htmlAttr = new { @class="CSS", @readonly="readonly"};
}
else {
    htmlAttr = new { @class="CSS" };
}

@Html.TextBoxFor( m => m.Field, htmlAttr)

由于表单中的大多数编辑控件都带有相同的CSS类,因此应满足大多数需求。如果发现某些控件上需要更多的类,只需添加其他htmlAttribute对象即可进行不同的类配置。

通过使用描述性变量名,这可以集中只读逻辑,并使您的剃须刀页面更加简洁。

答案 2 :(得分:0)

为了使代码更易于阅读,您可以使用可以声明的函数:

@functions
{
    private object GetAttributes()
    {
        if (ViewBag.IsAdmin !=null && ViewBag.IsAdmin)
        {
            return null;
        }

        return new { @readonly = "readonly" };
    }
}

然后您可以像这样使用它:

@Html.TextBoxFor(a => a.VSSLabel, GetAttributes())

在函数中,您可以添加需要添加到元素的任何属性:

return new { @class = "form-control", @readonly = "readonly", @required = "required" }

效果很好

答案 3 :(得分:0)

您可以编写如下扩展方法:

/* for .NET Core       */ using Microsoft.AspNetCore.Mvc.ViewFeatures;
/* for .NET Framework: */ using System.Web.WebPages.Html;

public static class HtmlHelpers
{
    public static object MakeReadonly(this object htmlAttributes, bool isReadonly)
    {
        if (isReadonly)
        {
            var dynamicHtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            dynamicHtmlAttributes["readonly"] = "readonly";
            return dynamicHtmlAttributes;
        }

        return htmlAttributes;
    }
}

用法:

@Html.TextBoxFor(..., new { @class = "form-control" }.MakeReadonly(true))

此方法的一个缺点是object上的扩展方法有点可疑,因为它们会在IntelliSense中的任何地方弹出。

如果您不喜欢这样做,建议您将htmlAttributes从匿名对象更改为ViewDataDictionary,并使扩展方法可以使用。