MVC EditorFor 可选只读

MVC EditorFor Optionally ReadOnly

昨天,经过大量测试,我得到了以下结果,可以根据 ViewBag.CanEdit;

的值有选择地将 readonly 属性应用于控件
@Html.EditorFor(m => m.Location, new { htmlAttributes = new { @class = "form-control", @readonly = (ViewBag.CanEdit == true ? Html.Raw("") : Html.Raw("readonly")) } })

基于这次测试的成功,我在项目的几个部分实施并测试了它。今天我开始编写代码的新部分并开始实施相同的代码,结果一直失败 - 每个控件都是 readonly.

当我检查控件时,它们的属性是 readonly 还是 readonly=readonly?然后我又回到昨天重构的代码,发现了同样的问题;无论 ViewBag.CanEdit?

的值如何,每个控件现在都是 readonly

谁能解释为什么这在昨天有效但今天却失败了?

试试这个

@Html.TextBoxFor(model => model.Location, !ViewBag.CanEdit 
    ? (object)new { @class = "form-control", @readonly ="readonly" } 
    : (object)new { @class = "form-control" })

作为更好的方法,我创建了这个方法,并且在我的项目中使用它,每当我需要这样的东西时。它会让你的代码更简洁。

首先,将此 class 添加到您的项目中:

 public static class HtmlBuildersExtended
    {
        public static RouteValueDictionary ConditionalReadonly(
            bool isReadonly,
            object htmlAttributes = null)
        {
            var dictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            if (isReadonly)
                dictionary.Add("readonly", "readonly");

            return dictionary;
        }
   }

然后您可以将代码更改为:

@Html.TextBoxFor(model => model.Location, 
      HtmlBuildersExtended.ConditionalReadonly(
          (bool)ViewBag.CanEdit, new { @class = "form-control" }));

或者如果你想使用 EditorFor 助手,那么:

@Html.EditorFor(model => model.Location,
             HtmlBuildersExtended.ConditionalReadonly((bool)ViewBag.CanEdit, 
                    new
                    {
                        htmlAttributes = new
                        {
                            @class = "form-control"
                        }
                    }));