2010-08-18 73 views
7

考慮以下設置:ReadOnly(true)是否可以使用Html.EditorForModel?

型號:

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 MVC,我的模型的一些屬性是隻讀的?我不想僅通過[ScaffoldColumn(false)]隱藏ProductID

回答

9

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。

+1

謝謝。我是這麼想的。太糟糕了,我不想使用[ScaffoldColumn(false)]並創建一個編輯器模板會有點失敗的目的... – 2010-08-18 13:01:48

+1

好吧@naso,有這樣的時刻,當我們在微軟詛咒,並繼續我們的日常工作:-)乾杯。 – 2010-08-18 13:53:05

11

我通過向我的「ReadOnly」類中的屬性添加UIHintAttribute來解決此問題。

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

然後,我只是在裏面加入了〜\查看\共享\ EditorTemplates \ ReadOnly.ascx文件到我的項目,這樣的:

<%= Model %> 

一個非常簡單的方法來添加自定義模板,你可以包括格式或其他。

+6

更酷的方法可以像[Brad Wilson的帖子](http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes)那樣繼承** DataAnnotationsModelMetadataProvider **類。 html),並簡單地添加這一行: 'if(metadata.IsReadOnly)metadata.TemplateHint =「ReadOnly」;' 結合我的文章中的ReadOnly.ascx文件,這應該使ReadOnly(true)屬性像你一樣工作期望。 ASP.NET MVC的岩石! – pwhe23 2011-02-25 21:17:36

+1

我知道這是舊的,但技術的作品。但是,這可能會導致數據被擦除。我的ReadOnly.cshtml是:@Model @ Html.HiddenFor(x => Model)確保總是返回值。 – Andiih 2015-03-30 13:53:08

2
<%@ 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) %> 
相關問題