Reputation: 3803
I was building a Html helper for one of my View using the following model when intellisense popped up sth i didnt know you could do. Basically my model is as follows
public class Mainclass
{
public List<main> mainset { get; set; }
// do sth to load and save model info
}
public class main
{
public personalinfo info { get; set; }
public addressinfo currentaddr { get; set; }
public addressinfo[] otheraddr { get; set; }
public telephone currenttel { get; set; }
public telephone[] othertel { get; set; }
}
public class personalinfo
{
public string Name { get; set; }
public string Surname { get; set; }
public string Ni { get; set; }
public string dob { get; set; }
public employer currentemployer { get; set; } //another class employer
public employer[] otheremployer { get; set; } //an array of employer class
}
What the intellisense popped up was (model => m.info.Name).
@if ( Model.mainset != null){
foreach ( var m in Model.subset )
{
<div class="editor-label">
@Html.LabelFor(model => m.info.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => m.info.Name)
@Html.ValidationMessageFor(model => m.info.Name)
<div class="editor-label">
}
So I was wondering how this statement works? Would it let me set the subfield in the main model directly without a helper or ajax or json?
Upvotes: 0
Views: 130
Reputation: 3046
Lambda is just an operator. The point is the ValidationMessageFor()
or EditorFor()
functions. They expects a Func<T>
parameter which is a delegate. With lambda you can pass the parameter, which is your model from the delegate signature and after the lambda operator you will write the method's implementation. So if you extends your model, you will see the new members in intellisense.
Note: The delegates must be instantiated before usage, but the MVC framework handles it dynamically when you create a strongly-typed view. Location of HtmlHelper instantiation for ASP.NET MVC
Upvotes: 1
Reputation: 151586
To clarify, you're not asking asking about lambda's in general, but about UNUSED
here?
foreach (var item in Model.Items)
{
@Html.DisplayFor(UNUSED => item.Foo)
}
It works, because you do pass the value of item.Foo
. The MVC helper can't bind it to a property of your model anymore though, so you can use this notation for display but not directly for edit-controls.
Upvotes: 1
Reputation: 65059
It's a lambda, and it isn't as magical as it appears (from a high level, anyway).
Best you learn from the source: Lambda Expressions - MSDN C# Programming Guide
Basically, in MVC, the methods you're using the lambda in will tie that property into your model when you post the form.
Upvotes: 2