Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLHelper, generating parameter of type "Expression<Func<TModel, TValue>> expression" out of property

I'm writing an HTML Helper for an editor. The idea is to get properties from the Model with attributes AutoGenerateField and build a table, each line of which contains a name of a field (also from the attribute) and a TextBox or a CheckBox containing actual value of the field.

I have a problem with HTMLHelper. Since I send the whole model to the helper and not one value, I cannot use methods such as TextBoxFor, as they need parameter, such as

"Expression<Func<TModel, TValue>> expression".

I'm using reflexion and I tried to send the property instead, still VisualStudio considers this as incorrect usage.

Below is simplified method for my HtmlHelper:

public static MvcHtmlString GenerateEditor<TModel>(this HtmlHelper<TModel> htmlHelper)
{
    var model = htmlHelper.ViewData.Model;
    var result = String.Empty;

    //generating container, etc ...

    foreach (var property in model.GetType().GetProperties())
    {
        var attr = property.GetCustomAttributes(typeof (DisplayAttribute), true).FirstOrDefault(); 
        if (attr == null) continue;
        var autoGenerate = ((DisplayAttribute)attr).AutoGenerateField;
        if(autoGenerate)
        {
           //here I'm building the html string 
           //My problem is in the line below:
           var r = htmlHelper.TextBoxFor(property); 
        }
    }
    return MvcHtmlString.Create(result);
}

Any ideas?

like image 965
Anelook Avatar asked Apr 19 '13 15:04

Anelook


1 Answers

How about just using the non-lambda overloads. : InputExtensions.TextBox()

if(autoGenerate)
{
   //here I'm building the html string 
   //My problem is in the line below:
   var r = htmlHelper.TextBox(property.Name); 
}
//not sure what you do with r from here...

If I'm not mistaken the name attribute of the form element is set to the property name even when you use the lambda version of the function so this should do the same thing.

I will try and verify what the lambda function does, you might be able to do the same since you have the TModel with you.


Update

From a quick look of things inside the source code of InputExtensions.cs, TextBoxFor calls eventually calls InputHelper() which eventually calls ExpressionHelper.GetExpressionText(LambdaExpression expression) inside ExpressionHelper.cs which from the cursory looks of things gets the member.Name for the name html attribute on the input element.

I can't quite verify it right now because I'm not on windows but I think the non-lambda function should suit your need. Do tell me how it goes?

like image 143
gideon Avatar answered Sep 28 '22 04:09

gideon