Dynamically call textboxfor with reflection

后端 未结 2 446
旧时难觅i
旧时难觅i 2021-01-07 05:12

The end result of what I am trying to do is build a form dynamically by reflecting an object and it\'s properties.

I\'ve created HtmlHelper methods that call TextBo

相关标签:
2条回答
  • 2021-01-07 05:54

    To get a property using reflection, use code like this:

    var prop = model_type.GetProperty(property_name);
    //then in your loop:
    prop.GetValue(model, null)
    

    Or if you're only going to get the property from one object, make it one line:

    model_type.GetProperty(property_name).GetValue(model, null);
    
    0 讨论(0)
  • 2021-01-07 05:59

    Ok, I solved this problem by building a lambda expression using the property name and the type of the object being passed in using the library System.Linq.Expressions.

    ParameterExpression fieldName = Expression.Parameter(typeof(object), property_name);
    Expression fieldExpr = Expression.PropertyOrField(Expression.Constant(model), property_name);
    Expression<Func<TModel, object>> exp = Expression.Lambda<Func<TModel, object>>(fieldExpr, fieldName);
    
    return helper.TextBoxFor(exp);
    

    Example:

    @{ Name myname = new Name();}
    @Html.FormTextBox("first", myname)
    

    fieldName builds an expression for the left hand side (first) and then fieldExpr builds the body of the expression with the class name and property name.

    exp ends up looking like this:

    first => value(DynamicForm.Models.Name).first
    
    0 讨论(0)
提交回复
热议问题