1

I want to create a custom asp.net mvc3 helper .

To use that helper, I should write syntax like below

@Html.DisplayMyCustomHelper(model => model.FullName)

Expected Output

Full Name (Value Picked from model's Display attribute)= Current Value Of Property

Eg:

public Class User
{
      [Display(Name="Full Name")]
      public string FullName{get;set;}
}

User = new User{FullName="Tom Cruise"};

Inside Razor

@model User
@Html.DisplayMyCustomHelper(model => model.FullName)

Expected OutPut

Full Name= Tom Cruise


How can i do this?

1

1 Answer 1

1
public static MvcHtmlString DisplayMyCustomHelper<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
    {
        const string format = "{0} = {1}";

        var metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, htmlHelper.ViewData);

        var model = metadata.Model;

        var result = string.Format(format, metadata.DisplayName, model == null ? string.Empty : model.ToString());

        return MvcHtmlString.Create(result);
    }
Sign up to request clarification or add additional context in comments.

4 Comments

it worked, i will accept it in few hours, just make one change in your answer , inside string.format replace "metadata.DisplayName" with "metadata.DisplayName ?? metadata.PropertyName"
@Praveen man, every piece of code written on stack overflow as answers is not the one to directly copy and paste in your production environment. The general idea is shown in my answer, and you are free do change what ever you want in it : )
he he, u are right. Could you suggest me how to do this | helper inside view = "@Html.MyDisplayFor(m => m)" , how to loop thru each property of model inside method "MyDisplayFor"
Take a look at bradwilson.typepad.com/blog/2009/10/…, section Tabular Layout, in Object template brad explains what you want

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.