我正在尝试创建一个我可以这样调用的扩展
@ Html.HiddenForSuperComplex(x => x.Abc)
我希望它以递归方式遍历该模型/表达式的属性,并为该模型/表达式中的所有字段创建Hiddens,以便保留模型。
我遇到了以下一行的障碍:
str = htmlHelper.HiddenForComplex<TProperty,mt>(a.Expression);
但我开始认为我走错了路......
public static MvcHtmlString HiddenForSuperComplex<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
TProperty t = htmlHelper.GetValue(expression);
Type type = typeof(TProperty);
MvcHtmlString retVal = new MvcHtmlString("");
var newExpression = expression.Body as NewExpression;
TModel model = htmlHelper.ViewData.Model;
foreach (MemberExpression a in newExpression.Arguments)
{
Type mt = a.Member.GetType();
MvcHtmlString str;
if (ModelUtil.IsSimpleEnough(mt))
{
string value = Convert.ToString(GetPropertyValue<TModel>(model, a));
str = htmlHelper.Hidden(value);
}
else
{
str = htmlHelper.HiddenForComplex<TProperty,mt>(a.Expression); //DOES NOT COMPILE
}
}
return retVal;
}
private static object GetPropertyValue<T>(T instance, MemberExpression me)
{
object target;
if (me.Expression.NodeType == ExpressionType.Parameter)
{
// If the current MemberExpression is at the root object, set that as the target.
target = instance;
}
else
{
target = GetPropertyValue<T>(instance, me.Expression as MemberExpression);
}
// Return the value from current MemberExpression against the current target
return target.GetType().GetProperty(me.Member.Name).GetValue(target, null);
}
public static MvcHtmlString HiddenForComplex<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
TProperty t = htmlHelper.GetValue(expression);
Type type = typeof(TProperty);
MvcHtmlString retVal = new MvcHtmlString("");
foreach (PropertyInfo info in t.GetType().GetProperties())
{
string value = info.GetValue(t).ToString();
//string value = (string)type.GetProperty(info.ToString()).GetValue(t, null);
MvcHtmlString str = htmlHelper.Hidden(value);
retVal = Concat(retVal, str);
}
return retVal;
}