如何通过 html 辅助方法更改或向 html 字段添加属性?

How to change or add attributes to html fields via html helper methods?

我想根据布尔值禁用或启用文本框,我创建了这个扩展方法:

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

这就是我使用的方式:

        <div class="col-md-10">
            @Html.MyTextBoxFor(model => model.Body, new { @class = "form-control"}, true)
        </div>

但它不起作用,我是 Htmlhelper 的新手 class,虽然不难理解,但我确实错过了一些东西!

编辑:

我试过这个简单的方法,找出问题所在:

public static IHtmlString MyTextBox(this HtmlHelper htmlHelper,object htmlAttributes, bool disabled)
        {
            IDictionary<string, object> attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            //var attrs = new Dictionary<string,string>();
            if (disabled)
            {
                attrs.Add("disabled", "disabled");
                attrs.Add("value", "txxxxxxt");
            }
            return htmlHelper.TextBox("txtbx", attrs);
        }

并且已经呈现: <input id="txtbx" name="txtbx" type="text" value="System.Collections.Generic.Dictionary``2[System.String,System.String]">

您的扩展方法的代码需要是

public static IHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
{
    IDictionary<string, object> attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    if (disabled)
    {
        attrs.Add("disabled", "disabled");
    }
    return htmlHelper.TextBoxFor(expression, attrs);
}

在您的第一个代码示例中,您使用了

return htmlHelper.TextBoxFor(expression, htmlAttributes);

返回原始属性,而不是包含 disabled 属性的更新属性。应该是

return htmlHelper.TextBoxFor(expression, attributes);

在你的第二个代码示例中,你使用 TextBox() 方法而不是 TextBoxFor() 并且第二个参数是值,而不是属性,它应该是

return htmlHelper.TextBox("txtbx", null, attrs);

尽管由于不正确的 name 属性,它不会绑定到您的 属性。

旁注:您不太清楚为什么要这样做。禁用的控件不提交值,因此您也可以将 属性 的值呈现为视图中的文本。如果您确实希望提交它的值,那么它应该是 readonly,而不是 disabled