0

I need to create Expression<Func<TModel, TValue>> from my model.

How to access the property in the model:

ViewModel.CustomFieldCollection[1].PrimaryFields[3].Value

where 1 & 3 are the indexes which will updated at runtime.

I am trying to creating an expression, to be passed to a HtmlHelper, to generate an HtmlString for me.

var viewModelExpParam = Expression.Parameter(typeof(ViewModel));

var fieldParam = Expression.Property(viewModelExpParam, "CustomFieldCollection[1]");

var expression = Expression.Lambda<Func<TModel, TValue>>(fieldParam, viewModelExpParam);

But the above code gives the error while creating fieldParam, as it is not the object but a collection object.

Can i generate an expression to access ViewModel.CustomFieldCollection[1].PrimaryFields[3].Value in HtmlHelper at runtime?

1 Answer 1

2

You could acces indexxed member via Item property (it's just a sample code, i haven't tried it out, you haven't provided any code for it :)):

var customFieldCollection = Expression.Property(viewModelExpParam,"CustomFieldCollection");
var fieldParam = Expression.Property(customFieldCollection , "Item", 
                         new Expression[] { Expression.Constant(1) });

And than:

var primaryFields = Expression.Property(fieldParam,"PrimaryFields");
var primaryFieldItem = Expression.Property(primaryFields , "Item", 
                             new Expression[] { Expression.Constant(3) });
var value = Expression.Property(primaryFieldItem, "Value");

var expression = Expression.Lambda<Func<TModel, TValue>>(value,  viewModelExpParam);
Sign up to request clarification or add additional context in comments.

7 Comments

got a probblem: Value is referenced from ViewModel as ViewModel.Value and not from ViewModel.CustomFieldCollection[1].PrimaryFields[3].Value
So you don't need all that stuff and can just call it as var value = Expression.Property(viewModelExpParam , "Value") ? And what is a problem?
sry, but i mean that as per above code my Input control is created with ID = Value, instead it should be created as ID = CustomFieldCollection[1].PrimaryFields[3].Value.
what are CustomFieldCollection and PrimaryFields ? Arrays? Lists? Dictionaries?
it would be difficult to showcase that. But thanks for pointing in correct direction. The expression is generated with the hierarchy, i believe the problem is with the control generation. I will mark it as answer as it does the purpose. Thanks! :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.