Isaac Bolinger
Isaac Bolinger

Reputation: 7388

How can I turn a lambda expression specifying a property into an asp.net mvc compatible 'name' string representing the same?

Assume

string value = ViewModelObject.SomeList[n].AnotherList[m].SomeProperty.ToString() //value is '5'

I need to turn this:

Expression<Func<ViewModelObjectType, object>> exp = x => x.SomeList[n].AnotherList[m].SomeProperty 

into

<input type='hidden' name='SomeList[n].AnotherList[m].SomeProperty' value='5'/>

where n and m are integers.

I'm betting someone's solved this before. I want to bind my javascript control to my page viewmodel in a type safe manner. I'm playing around with the expression classes now and I can extract the property as a string but the rest of it I haven't figured out yet.

Thanks!

Upvotes: 2

Views: 193

Answers (2)

Isaac Bolinger
Isaac Bolinger

Reputation: 7388

I had to use this courtesy of: ExpressionHelper.GetExpressionText(expression) not returning the name of my property

static public string GetExpressionText(LambdaExpression p)
{
    if (p.Body.NodeType == ExpressionType.Convert || p.Body.NodeType == ExpressionType.ConvertChecked)
    {
        p = Expression.Lambda(((UnaryExpression)p.Body).Operand,
            p.Parameters);
    }
    return ExpressionHelper.GetExpressionText(p);
}

My NodeType was always evaluating as ExpressionType.Convert

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039428

The @Html.HiddenFor helper seems to do what you need:

@Html.HiddenFor(x => x.SomeList[n].AnotherList[m].SomeProperty)

But if for some reason you cannot rely on what's already built into the framework you could always roll your own stuff using the ExpressionHelper.GetExpressionText method which is what the ASP.NET MVC built-in helpers are already using:

public static class HtmlExtensions
{
    public static string Foo<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> ex)
    {
        return ExpressionHelper.GetExpressionText(ex);
    }
}

and then in your strongly typed view use it like that:

<input type='hidden' name='@Html.Foo(x => x.SomeList[n].AnotherList[m].SomeProperty)' value='5'/>

Upvotes: 4

Related Questions