加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ReadOnly(true)是否与Html.EditorForModel一起使

发布时间:2020-12-16 04:26:46 所属栏目:asp.Net 来源:网络整理
导读:请考虑以下设置: 模型: 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.ViewPageM
请考虑以下设置:

模型:

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

结果如下:

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

解决方法

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读