代码之家  ›  专栏  ›  技术社区  ›  Atanas Korchev

ReadOnly(true)与Html.EditorForModel?

  •  7
  • Atanas Korchev  · 技术社区  · 15 年前

    考虑以下设置:

    型号:

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

    alt text

    我以为 ProductID 属性不能通过 ReadOnly(true) 属性。是否支持此功能?如果没有,有什么方法可以暗示吗ASP.NET我的模型的某些属性是只读的?我不想躲起来 产品ID 通过 [ScaffoldColumn(false)]

    3 回复  |  直到 15 年前
        1
  •  9
  •   Mikayil Abdullayev    11 年前

    ReadOnly Required 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。

        2
  •  11
  •   pwhe23    14 年前

    我通过向类“”的属性添加uihintatAttribute来解决此问题 ".

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

    然后我简单地添加了一个 将此文件添加到我的项目中:

    <%= Model %>
    

    一个添加自定义模板的非常简单的方法,你可以包括格式化或者其他什么。

        3
  •  2
  •   McDowell rahul gupta    13 年前
    <%@ 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) %>