关于c#:MVC编辑器

MVC EditorFor Optionally ReadOnly

昨天,经过广泛测试,我得到了以下内容,可以根据ViewBag.CanEdit;

的值将readonly属性可选地应用于控件。

1
@Html.EditorFor(m => m.Location, new { htmlAttributes = new { @class ="form-control", @readonly = (ViewBag.CanEdit == true ? Html.Raw("") : Html.Raw("readonly")) } })

基于这项测试的成功,我在项目的多个部分中实施和测试了它。今天,我从代码的新部分开始,并开始实施相同的代码,只是为了使它始终失败-每个控件都是readonly

当我检查控件时,它们是否具有readonlyreadonly=readonly作为属性?然后,我回到昨天重构的代码中,发现同样的问题。现在,每个控件都是readonly,而不管ViewBag.CanEdit

的值如何

任何人都可以解释为什么昨天可以解决这个问题,但是今天失败了吗?


作为一种更好的方法,我创建了此方法,并在需要时在项目中使用它。这将使您的代码更加整洁。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 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;
        }
   }

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

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

或者如果您想使用EditorFor助手,则:

1
2
3
4
5
6
7
8
9
@Html.EditorFor(model => model.Location,
             HtmlBuildersExtended.ConditionalReadonly((bool)ViewBag.CanEdit,
                    new
                    {
                        htmlAttributes = new
                        {
                            @class ="form-control"
                        }
                    }));

试试这个

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