gpt4 book ai didi

c# - 如何在 EditorFor 中访问 C# 模型属性

转载 作者:太空狗 更新时间:2023-10-29 22:53:02 26 4
gpt4 key购买 nike

我有一个像下面这样的模型:

public class CreateStockcheckJobModel
{
[Engineer(true)]
public EngineerModel Engineer { get; set; }
}

我正在渲染 Engineer View<CreateStockcheckJobModel> 中的属性(property)使用 Html.EditorFor(m => m.Engineer, "EngineerEditor") .

如何访问 Engineer 中的值我的部分 View ( true ) 中的代码中的属性(在本例中为 EngineerEditor.ascx )?


下面是我的编辑器代码

<%@ Control Language="C#" Inherits="ViewUserControl<EngineerModel>" %>
<% if (PropertyImRenderingHasAttributeWithTrueBooleanValue) // What goes here?
{ %>
<p>Render one thing</p>
<% }
else
{ %>
<p>Render another thing</p>
<% } %>

我知道反射,但是我不确定如何使用它,因为属性没有添加到 EngineerModel它被添加到 Engineer 中的类CreateStockcheckJobModel 的属性(property)类(class)。如果我能得到 PropertyInfo我从编辑器代码中呈现然后我会被排序,但我不知道如何获取该信息。如果我沿着枚举 CreateStockcheckJobModel 中的所有属性的路线前进类,那么如果我有多个 EngineerModel,我就会遇到问题属性(一个可能具有 True 的属性,另一个可能具有 False )。

最佳答案

这可以在 ASP.NET MVC 3 和更高版本中通过实现 IMetadataAware 轻松完成。自定义 EngineerAttribute 上的接口(interface):

public class EngineerAttribute : Attribute, IMetadataAware
{
public EngineerAttribute(bool isFoo)
{
IsFoo = isFoo;
}

public bool IsFoo { get; private set; }

public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["IsFoo"] = IsFoo;
}
}

然后在模板中:

<%@ Control Language="C#" Inherits="ViewUserControl<EngineerModel>" %>
<%
var isFoo = (bool)ViewData.ModelMetadata.AdditionalValues["IsFoo"];
%>
<% if (isFoo) { %>
<p>Render one thing</p>
<% } else { %>
<p>Render another thing</p>
<% } %>

不幸的是,此接口(interface)在 ASP.NET MVC 2 中不存在。要实现相同的功能,您可以编写自定义元数据提供程序:

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName
)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var engineer = attributes.OfType<EngineerAttribute>().FirstOrDefault();
if (engineer != null)
{
metadata.AdditionalValues["IsFoo"] = engineer.IsFoo;
}
return metadata;
}
}

您将在 Application_Start 中注册以替换默认的:

ModelMetadataProviders.Current = new MyMetadataProvider();

现在您可以使用 ViewData.ModelMetadata.AdditionalValues["IsFoo"] 以与我之前展示的方式相同的方式在模板中访问此元数据。显然,您可以将任意复杂的对象放入 AdditionalValues 属性中,而不仅仅是 bool 值。

您还可以找到 following article对元数据很有用。

关于c# - 如何在 EditorFor 中访问 C# 模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12456455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com