3

I was reading one of Brad Wilson's articles:

ASP.NET MVC 2 Templates, Part 2: ModelMetadata

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html

Let's assume that on my ASP.NET MVC 3 App, I have the following model:

public class Contact {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

And here is my view:

@model MyApp.Models.Contact

<h2>Contact</h2>

@Html.EditorForModel()

and I have a Contact.cshtml file inside ~/Views/Shared/EditorTemplates/ path.

My question is how I can reach out to ModelMetadata of each model property. For example, like following:

Contact.cshtml

@model MyApp.Models.Contact

<input type="text" placeholder="@Model.FirstName.GetItsMetaData().Watermark" 
       value="@Model.FirstName" />

NOTE: GetItsMetaData method is something which I totally made up. I am just trying to get to MedelMetadata of the property. Doesn't have to be that way.

EDIT

I found another similar question:

ModelMetadata for complex type in editortemplate in asp.net mvc

and the answer is this:

@{
    var metadata = ModelMetadata
        .FromLambdaExpression<TestThing, string>(x => x.Test2, ViewData);
    var watermak = metadata.Watermark;
}

But it is quite verbose to do this for every single property of my model, isn't it?

Community
  • 1
  • 1
tugberk
  • 57,477
  • 67
  • 243
  • 335
  • Hi tugberk, I just wanted to answer to your question "*Performance difference between Entry(entity) and Entry(entity) on Entity Framework 4.2*" but at the same moment you deleted your question, lol. Point is: *The compiler* will select the generic overload when you call `Entry(entity)` (generic type inference). The same method is called no matter if you specify the generic parameter or not. (The only exception is if `entity` is of type `object` *at compile time*, then the non-generic overload is called.) Because the compiler calls the same method there is no performance difference. – Slauma Nov 19 '11 at 12:07
  • @Slauma yeah, they think the question was stupid and I didn't wanna get into an argument so I deleted it. Thanks a lot! – tugberk Nov 19 '11 at 12:10

1 Answers1

4

It is less verbose to create an HtmlHelper to use for this purpose. The helper would look like this:

    public static string WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        return metadata.Watermark;
    }

You would use it as follows in your example:

@model MyApp.Models.Contact  

<input type="text" placeholder="@Html.WatermarkFor(x => x.FirstName)"   
    value="@Model.FirstName" /> 
counsellorben
  • 10,924
  • 3
  • 40
  • 38