asp.net mvc - How to get the column titles from the Display(Name=) DataAnnotation for a strongly typed list scaffold view at runtime? -
how [display(name="some title")]
dataannotations "some title" rendered in list scaffold view's output?
i create typed list scaffold view class:
public class companyholiday { [key] public int id { get; set; } [required] [display(name = "datum")] [datatype(system.componentmodel.dataannotations.datatype.date)] public datetime date { get; set; } [required] [stringlength(50)] [display(name = "feiertag name")] public string name { get; set; } }
the view looks this:
@model ienumerable<zeiterfassung.domain.companyholiday> @{ viewbag.title = "year"; } <h2>year</h2> <p> @html.actionlink("create new", "create") </p> <table> <tr> <th></th> <th> date </th> <th> name </th> </tr> @foreach (var item in model) { <tr> <td> @html.actionlink("edit", "edit", new { id=item.id }) | @html.actionlink("details", "details", new { id=item.id }) | @html.actionlink("delete", "delete", new { id=item.id }) </td> <td> @string.format("{0:g}", item.date) </td> <td> @item.name </td> </tr> } </table>
however, don't want "date" , "name" in table header. want "datum" , "feiertag name" rendered there dynamically.
the actual column header titles should come display dataannotation.
how do this?
bit of old topic, came extension method handle this.
lets model is:
public class mymodel { [display(name = "some property")] public string someprop { get; set; } }
drop method static class:
namespace web.extensions { public static class htmlhelperextensions { public static mvchtmlstring displaynamefor<tmodel, tproperty>(this htmlhelper<ienumerable<tmodel>> helper, expression<func<tmodel, tproperty>> expression) { var name = expressionhelper.getexpressiontext(expression); name = helper.viewcontext.viewdata.templateinfo.getfullhtmlfieldname(name); var metadata = modelmetadataproviders.current.getmetadataforproperty(() => activator.createinstance<tmodel>(), typeof(tmodel), name); return new mvchtmlstring(metadata.displayname); } } }
then in view, taking ienumerable<mymodel>
, can use this:
@using web.extensions @model ienumerable<mymodel> <table> <tr> <th> @html.displaynamefor(m => m.avgeleccost) </th>
the generated html be:
<th> property </th>
hope helps!
Comments
Post a Comment