考虑以下设置:
型号:
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>
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Product
{
ProductID = 1,
Name = "Banana"
});
}
}
结果是这样的:
我预计 ProductID
属性无法通过 ReadOnly(true)
属性进行编辑。支持吗?如果没有,有什么方法可以提示 ASP.NET MVC 我的模型的某些属性是只读的吗?我不想只是通过 [ScaffoldColumn(false)]
隐藏 ProductID
。
最佳答案
我通过向“ReadOnly”类的属性添加 UIHintAttribute 解决了这个问题。
[UIHint("ReadOnly")]
public int ClassID { get; set; }
然后我只是将一个 ~\Views\Shared\EditorTemplates\ReadOnly.ascx 文件添加到我的项目中,其中包含以下内容:
<%= Model %>
添加自定义模板的非常简单的方法,您可以包含格式或其他内容。
关于asp.net-mvc - ReadOnly(true) 是否可以与 Html.EditorForModel 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510081/