o.Prop) %> \\uses Html.My in the My.ascx template 和 he-6ren">
gpt4 book ai didi

asp.net-mvc - 在 html helper 中获取属性的值

转载 作者:行者123 更新时间:2023-12-01 07:05:50 25 4
gpt4 key购买 nike

我有一个自定义助手“我的”,我想在其中获取已用属性的值。

我这样称呼它:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<VMThatHasAllTheseProps>" %>
<%=Html.My("Hi") %>
<%=Html.EditorFor(o => o.Prop) %> \\uses Html.My in the My.ascx template

<%=Html.My("[0].My") %>
<%=Html.My("[1].My") %>

和 helper :
public static MvcHtmlString My(this HtmlHelper html, string prop, object value = null)
{
//get value of the used property here
}

目前我喜欢这样:
 //get val from model
if (value == null && html.ViewData.Model != null)
{
var p = TypeDescriptor.GetProperties(html.ViewData.Model).Find(prop, false);

if (p != null) value = p.GetValue(html.ViewData.Model);
}

//get val from model metada
if(value == null && html.ViewData.ModelMetadata != null)
{
var p = TypeDescriptor.GetProperties(html.ViewData.ModelMetadata.Model).Find(prop, false);
if (p != null) value = p.GetValue(html.ViewData.ModelMetadata.Model);
}

//get val from viewdata
if (value == null && html.ViewData.ContainsKey(prop))
value = html.ViewData[prop];

但显然它不适用于 "[0].My"

最佳答案

ViewData.Eval(字符串表达式)?

ViewDataDictionary.Eval Method (System.Web.Mvc)

关于asp.net-mvc - 在 html helper 中获取属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4607266/

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