Reputation: 481
In .Net MVC we use Editor Templates to output HTML. So in a View we write something like below and the Editor Template for String (Description is a string object) outputs the correct HTML and controls for the string type:
@Html.EditorFor(model => model.Entity.Description)
I want to create an Editor Template that is able to use\recreate the Lambda expression that I used in the view i.e. model.Entity.Description. In the Editor Template I can retrieve the property name in this case Description however I'd like to be able to retrieve the Lambda expression in the Editor Template that I used in the View i.e. model => model.Entity.Description An example Editor Template is below - I want to replace MYLAMBDAEXPRESSIONHERE with the relevant expression dynamically i.e. model => model.Entity.Description:
@model IDictionary Fields //Or some object that also contains the lambda expression
@using System.Collections;
@using System.Collections.Generic;
@using Mallon.Core.Artifacts;
@{
var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;
FieldAccessOptionality access = (FieldAccessOptionality)Model[fieldName];
switch(access)
{
case FieldAccessOptionality.None:
break;
case FieldAccessOptionality.Mandatory:
<div class="editor-label">
@Html.LabelFor(MYLAMBDAEXPRESSIONHERE)
</div>
<div class="editor-field">
@Html.EditorFor(MYLAMBDAEXPRESSIONHERE)
@Html.ValidationMessageFor(MYLAMBDAEXPRESSIONHERE)
</div>
break;
}
}
Upvotes: 3
Views: 1042
Reputation: 10313
You cannot access the lambda expression in the template but you can use the ModelMetadata in order to obtain further information. For example,
@ViewData.ModelMetadata.PropertyName
gives you the property name. In your example, "Description".
Upvotes: 2