Get property value inside html helper

I have a custom My helper, and I would like to get the value of the property used in it.

I call it this way:

<%@ 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") %>

and assistant:

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

At the moment I like it:

 //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];

but obviously this does not work for "[0].My"

+3
source share
1 answer

ViewData.Eval (string expression)?

ViewDataDictionary.Eval Method (System.Web.Mvc)

+6
source

Source: https://habr.com/ru/post/1783686/


All Articles