Omu
Omu

Reputation: 71198

get property's value inside html helper

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

I'm calling it like this:

<%@ 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 the helper:

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

at the moment I do like this:

 //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 it doesn't work for the "[0].My"

Upvotes: 4

Views: 3640

Answers (1)

takepara
takepara

Reputation: 10433

ViewData.Eval(string expression)?

ViewDataDictionary.Eval Method (System.Web.Mvc)

Upvotes: 6

Related Questions