I would like to create a helper that can be used like
@Html.MyHelperFor(m => m.Name)
this should return for example
<span name="Name" data-something="Name"></span>
if it is @Html.MyHelperFor(m => m.MailID)
This should return
<span name="MailID" data-something="MailID"></span>
I should be able to access the Property name in the helper method to make this type of helper ,I think.
How can I do this?
You can do something like (the following will take additional HTML attributes too).
Following up on mattytommo's answer, this works great but there is only a small problem when used with complex objects, such as if you are using this code for a property inside an EditorTemplate.
Instead of
If using MVC4, you can change it to
or for MVC3 and below
Full code:
You can use the
FromLambaExpression
method fromModelMetadata
like this:The
ModelMetadata
class is in theSystem.Web.Mvc
namespace. TheFromLambdaExpression
method is what the built in helpers use so then you can be sure your helper will function the same as the built in helpers. By placing theCustomHelpers
class inside theSystem.Web.Mvc.Html
namespace you can then access your helper like you would the other helpers, i.e.@Html.MyHelperFor()
.This should get you started. This function directly returns the property name but you should be able to convert this into the extension you are looking for with a little work. This example has the correct method signature and the call to ExpressionHelper to get the name of your property.