MVC 编辑器可选只读

本文关键字:只读 编辑器 MVC | 更新日期: 2023-09-27 18:30:25

昨天,经过广泛的测试,我得到了以下内容,可以选择地将只读属性应用于基于 ViewBag.CanEdit 值的控件;

@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

谁能解释为什么这在昨天会起作用,但今天会失败?

MVC 编辑器可选只读

作为一种更好的方法,我已经创建了这种方法,每当我需要这样的东西时,我都会在我的项目中使用它。它将使您的代码更加干净。

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

 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"
                        }
                    }));

试试这个

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