【问题标题】:Does ReadOnly(true) work with Html.EditorForModel?ReadOnly(true) 是否适用于 Html.EditorForModel?
【发布时间】:2010-08-18 08:07:24
【问题描述】:

考虑以下设置:

型号:

public class Product
{
    [ReadOnly(true)]
    public int ProductID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

查看:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MvcApplication4.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.EditorForModel() %>
</asp:Content>

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Product
            {
                ProductID = 1,
                Name = "Banana"
            });
    }
}

结果是这样的:

我期待ProductID 属性不能通过ReadOnly(true) 属性进行编辑。这支持吗?如果没有,有什么方法可以提示 ASP.NET MVC 我的模型的某些属性是只读的?我不想通过[ScaffoldColumn(false)] 隐藏ProductID

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 readonly-attribute


    【解决方案1】:

    我通过向“ReadOnly”类的属性添加 UIHintAttribute 解决了这个问题。

    [UIHint("ReadOnly")]
    public int ClassID { get; set; }
    

    然后我简单地在我的项目中添加了一个 ~\Views\Shared\EditorTemplates\ReadOnly.ascx 文件:

    <%= Model %>
    

    添加自定义模板的一种非常简单的方法,您可以包含格式或其他内容。

    【讨论】:

    • 一个更酷的方法可能是子类化 DataAnnotationsModelMetadataProvider 类,就像在Brad Wilson's post 中一样,并简单地添加这一行:if (metadata.IsReadOnly) metadata.TemplateHint = "ReadOnly"; 在我的帖子中结合 ReadOnly.ascx 文件,这应该使 ReadOnly(true) 属性像您期望的那样工作。 ASP.NET MVC 震撼!
    • 我知道这是旧的,但该技术有效。但是,它可能会导致数据被删除。我的 ReadOnly.cshtml 是:@Model @Html.HiddenFor(x=>Model) 以确保始终返回该值。
    【解决方案2】:

    ReadOnlyRequired 属性将由元数据提供程序使用,但不会被使用。如果你想摆脱EditorForModel 的输入,你需要一个自定义模板,或者[ScaffoldColumn(false)]

    自定义模板~/Views/Home/EditorTemplates/Product.ascx

    <%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>
    
    <%: Html.LabelFor(x => x.ProductID) %>
    <%: Html.TextBoxFor(x => x.ProductID, new { @readonly = "readonly" }) %>
    
    <%: Html.LabelFor(x => x.Name) %>
    <%: Html.TextBoxFor(x => x.Name) %>
    

    另请注意,默认模型绑定器不会将值复制到具有[ReadOnly(false)] 的属性中。此属性不会影响默认模板呈现的 UI。

    【讨论】:

    • 谢谢。我是这么想的。太糟糕了,我不想使用 [ScaffoldColumn(false)] 并且创建编辑器模板会破坏目的......
    • 好吧@naso,有时候我们只是在微软诅咒并继续我们的日常工作:-)干杯。
    【解决方案3】:
    <%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>
    
    <%: Html.LabelFor(x => x.ProductID) %>
    <%: Html.TextBoxFor(x => x.ProductID, new { @readonly = true }) %>
    
    <%: Html.LabelFor(x => x.Name) %>
    <%: Html.TextBoxFor(x => x.Name) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-12
      • 2020-08-15
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2019-11-22
      • 1970-01-01
      相关资源
      最近更新 更多