3

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;
   }
}
4
  • You mean, displaying a property which name is only known at runtime ? Commented Nov 5, 2013 at 9:52
  • I want to display the 'model => model.Entity.Description' property in the editor. I'm looking at HTML Helpers which may offer me a solution to pass the Lambda expression as a parameter. Commented Nov 5, 2013 at 10:27
  • It's still not clear what problem have you faced, i.e. why cannot you simply write lambda where you want it to be? Commented Nov 5, 2013 at 10:36
  • I've edited the original post with some additional details for clarity. Basically I want to access the lambda expression I used in the View in the Editor Template. Commented Nov 5, 2013 at 10:48

1 Answer 1

2

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".

Sign up to request clarification or add additional context in comments.

Comments

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.