ReadOnly(true)是否与Html.EditorForModel一起使用?

时间:2010-08-18 08:07:25

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

考虑以下设置:

型号:

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我的模型的某些属性是只读的?我不想通过ProductID隐藏[ScaffoldColumn(false)]

3 个答案:

答案 0 :(得分:11)

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

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

然后我只是将〜\ Views \ Shared \ EditorTemplates \ ReadOnly.ascx 文件添加到我的项目中:

<%= Model %>

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

答案 1 :(得分: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。

答案 2 :(得分: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) %>