难道只读(真)与Html.EditorForModel工作? [英] Does ReadOnly(true) work with Html.EditorForModel?

查看:112
本文介绍了难道只读(真)与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"
            });
    }
}

有结果是这样的:

There result is this:

我期待的的ProductID 财产不会是通过只读(真)属性编辑。是否支持?如果不是有没有办法暗示ASP.NET MVC,我的模型的某些属性是只读的?我不希望只是躲在的ProductID 通过 [ScaffoldColumn(假)]

I was expecting that the ProductID property was not going to be editable via the ReadOnly(true) attribute. Is this supported? If not is there any way to hint ASP.NET MVC that some properties of my model are read-only? I would not like to just hide ProductID via [ScaffoldColumn(false)].

推荐答案

只读要求属性将被由元数据提供者所消耗,但将不被使用。如果你想摆脱的投入与 EditorForModel 你需要一个自定义模板,或 [ScaffoldColumn(假)]

The ReadOnly and Required attributes will be consumed by the metadata provider but won't be used. If you want to get rid of the input with EditorForModel you'll need a custom template, or [ScaffoldColumn(false)].

有关自定义模板〜/查看/主页/ 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) %>

另外请注意,默认模式粘结剂将不是一个值复制到属性与 [只读(假)] 。此属性不会影响由默认模板呈现的UI。

Also note that the default model binder won't copy a value into a property with [ReadOnly(false)]. This attribute won't influence the UI rendered by the default templates.

这篇关于难道只读(真)与Html.EditorForModel工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆