ASP.net-Core如何在每个实例中使用不同的[displayname]值?
创始人
2024-09-17 02:00:38
0

要实现这个功能,我们需要使用[Display]属性来覆盖Model的默认DisplayName属性。在覆盖时,我们需要为每个实例提供不同的值。

下面是一个例子,其中我们有一个名为"PersonModel"的模型类,其中包含一个ID,名字和年龄属性:

public class PersonModel { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } }

如果我们想要为每个实例提供不同的DisplayName,我们可以在该属性上使用[Display]属性,如下所示:

public class PersonModel { public int ID { get; set; }

[Display(Name = "First Name")]
public string FirstName { get; set; }

[Display(Name = "Last Name")]
public string LastName { get; set; }

public int Age { get; set; }

}

在这个例子中,我们已经覆盖了默认的DisplayName属性,并为每个实例提供了不同的值。在视图中,我们可以使用@Html.EditorFor(x => x.FirstName)和@Html.EditorFor(x => x.LastName)来显示这些属性。

如果我们想动态地为每个实例提供不同的值,我们可以从数据库或其他数据源中获取它们,然后将它们分配给[Display]属性,就像下面这样:

var person = _dbContext.Persons.Find(id);

person.FirstName = person.FirstName; person.LastName = person.LastName;

var property = TypeDescriptor.GetProperties(person)["FirstName"]; var display = property.Attributes[typeof(DisplayAttribute)] as DisplayAttribute; display.Name = "New Display Name";

请注意,如果您想在使用Name属性时向其传递变量,则不能使用字符串插值,因为[Display]属性需要一个常量值。在这种情况下,您可以使用下面的语法:

var displayName = "New Display Name"; property.Attributes[typeof(DisplayAttribute)] = new DisplayAttribute {

相关内容

热门资讯

今日科普!微信卡五星辅助器,微... 今日科普!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)攻略;1.微信卡五星辅助器 选牌创建...
重大通报!微乐自建房辅助工具挂... 重大通报!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)app1、打开软件启动之后找到中间...
让我来分享经验!微乐自建房辅助... 让我来分享经验!微乐自建房辅助工具免费app,微乐自建房脚本免费入口(开挂自建房)脚本1、微乐自建房...
记者揭秘!微乐小程序自建房辅助... 记者揭秘!微乐小程序自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)软件微乐小程序自建房辅助...
必看攻略!微乐自建房辅助工具免... 必看攻略!微乐自建房辅助工具免费app,微乐家乡麻将自建房辅助app(开挂自建房)攻略1、每一步都需...
必备攻略!微乐家乡麻将自建房辅... 必备攻略!微乐家乡麻将自建房辅助app,微乐家乡麻将自建房辅助app(开挂自建房)技巧1、必备攻略!...
查到实测辅助!微信卡五星辅助器... 查到实测辅助!微信卡五星辅助器,微乐家乡麻将自建房辅助app(开挂自建房)教程1、超多福利:超高返利...
传递经验!微乐自建房辅助工具挂... 传递经验!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)技巧1、操作简单,无需微乐自建房辅...
一分钟教你!微信卡五星辅助器,... 一分钟教你!微信卡五星辅助器,微乐家乡麻将自建房辅助app(开挂自建房)插件1、这是跨平台的微乐家乡...
传递经验!微乐小程序自建房辅助... 传递经验!微乐小程序自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)脚本传递经验!微乐小程序...