Question

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?

Était-ce utile?

La solution

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" /> 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top