1

I have some questions about html helpers in ASP.NET MVC Framework. So...

  1. Can I override a inbuilt helper like @Html.HiddenFor?
  2. Should I override, or create a CustomHiddenFor one?
  3. While creating a Custom one, how can I change the value from ModelMetaData and then call the inbuilt helper? Eg:

    public static MvcHtmlString HiddenSecuredFor<TModel, TProperty>
        (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes,bool secured)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var name = ExpressionHelper.GetExpressionText(expression);
        if (!secured)
        {
            return htmlHelper.HiddenFor(expression,htmlAttributes);
        }
    
            // Here I want to change the value 
            // from the TModel lets say the property is x => x.Name
            // And I want to make the Name = "Mr. " + Name
    
        // Call the inbuild helper with the expression value changes.
        return htmlHelper.HiddenFor(expression, htmlAttributes);
    }
    
Cristian E.
  • 3,116
  • 7
  • 31
  • 61

1 Answers1

3
  1. Yes - How can I override the @Html.LabelFor template?
  2. It depends - If you are adding functionality you always need and you want other developers to use without having to know about it, overriding is a good option. Otherwise, creating a custom one that calls the original is a good approach.
Community
  • 1
  • 1
severin
  • 5,203
  • 9
  • 35
  • 48
  • Thank you for your answer and for the link. But what about the 3. ? – Cristian E. Mar 04 '14 at 09:26
  • I'm not sure if I understand exactly what you mean, but the metadata ultimately translates into htmlAttributes, so if you wish to add your own you can pass them on as htmlAttributes. Example: http://pastebin.com/BbzPSkhN – severin Mar 04 '14 at 09:43
  • 1
    `htmlAttributes` is simple to override but, how to change the actual value from the `expression`. When writing `@Html.HiddenFor(x => x.Name)`, we have 1. The expression tree which holds the property info(name,type etc). 2. The `@model MyNiceViewModel` which has the value of `x => x.Name`. How to change that value? – Cristian E. Mar 04 '14 at 09:48
  • I'm not sure if you can do that. My only suggestion would be to build the entire result yourself, like the initial example. – severin Mar 04 '14 at 09:55
  • Thank you for your suggestion. I'll do some experiments. If a better solution wouldn't appear from the community(including from you :)), I'll mark yours as an answer. – Cristian E. Mar 04 '14 at 10:01