【问题标题】:MVC EditorFor Optionally ReadOnlyMVC EditorFor 可选只读
【发布时间】:2016-01-15 15:04:40
【问题描述】:

昨天,经过大量测试,我得到了以下内容,可以根据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

谁能解释一下为什么这在昨天可行,但今天却失败了?

【问题讨论】:

    标签: c# asp.net-mvc mvc-editor-templates readonly-attribute


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 感谢 Nitin,我已经开始重构我的代码以使用此代码,但是我真的很想知道为什么我的示例中的代码最初可以工作,因为我最终浪费了很多时间。
    • 已相应更新。只是我从stackoverflow.com/questions/9086104/… 中获取了所谓的“参考”;)
    【解决方案2】:

    作为一种更好的方法,我创建了这个方法,并在我的项目中使用它,只要我需要这样的东西。它会让你的代码更干净。

    首先,将这个类添加到你的项目中:

     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 helper,那么:

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

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 2015-05-23
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 2013-10-03
      相关资源
      最近更新 更多