How with lambda function in MVC3
Posted
by
doogdeb
on Stack Overflow
See other posts from Stack Overflow
or by doogdeb
Published on 2012-09-08T15:30:53Z
Indexed on
2012/09/08
15:38 UTC
Read the original article
Hit count: 152
I have a model which contains view models for each view. This model is held in session and is initialised when application starts. I need to be able to populate a field from one view model with the value from another so have used a lambda function. Below is my model. I am using a lambda so that when I get Test2.MyProperty it will use the FunctionTestProperty to retrieve the value from Test1.TestProperty.
public class Model
{
public Model()
{
Test1 = new Test1()
Test2 = new Test2(FunctionTestProperty () => Test1.TestProperty)
}
}
public class Test1
{
public string TestProperty { get; set; }
}
public class Test2
{
public Test2() : this (() => string.Empty)
{}
public Test2(Func<string> functionTestProperty)
{
FunctionTestProperty = functionTestProperty;
}
public Func<string> FunctionTestProperty { get; set; }
public string MyProperty
{
get{ return FunctionTestProperty() ?? string.Empty; }
}
}
This works perfectly when I first run the application and navigate from Test1 to Test2; I can see that when I get the value for MyProperty it calls back to Model constructor and retrieves the Test1.TestProperty value. However when I then submit the form (Test2) it calls the default constructor which sets it to string.Empty. So if I go back to Test1 and back to Test2 again it always then calls the Test2 default constructor. Does anyone know why this works when first running the application but not after the view is submitted, or if I have made an obvious mistake?
© Stack Overflow or respective owner