C# 从MemberExpression获取链接属性名称
我正在为MVC创建一个表单生成器,我想用以下方式模拟Razor对链接属性的处理:C# 从MemberExpression获取链接属性名称,c#,linq,C#,Linq,我正在为MVC创建一个表单生成器,我想用以下方式模拟Razor对链接属性的处理: builder.TextBoxFor(x => x.User.Email); 这将以与Razor相同的方式产生以下结果: <input id="User_Email" name="User.Email" type="textbox" /> 我如何调整这一点,使x.User.Email产生User.Email,而不仅仅是Email,就像现在这样?您需要一点递归: private static s
builder.TextBoxFor(x => x.User.Email);
这将以与Razor相同的方式产生以下结果:
<input id="User_Email" name="User.Email" type="textbox" />
我如何调整这一点,使
x.User.Email
产生User.Email
,而不仅仅是Email
,就像现在这样?您需要一点递归:
private static string GetPropertyPath<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
var propertyPath = new Stack<string>();
var body = (MemberExpression)expression.Body;
do
{
propertyPath.Push(body.Member.Name);
// this will evaluate to null when we will reach ParameterExpression (x in "x => x.Foo.Bar....")
body = body.Expression as MemberExpression;
}
while (body != null);
return string.Join(".", propertyPath);
}
私有静态字符串GetPropertyPath(表达式)
{
var propertyPath=新堆栈();
var body=(MemberExpression)expression.body;
做
{
propertyPath.Push(body.Member.Name);
//当我们到达ParameterExpression(x=>x.Foo.Bar中的x…)时,这将计算为null
body=body.Expression作为MemberExpression;
}
while(body!=null);
返回字符串.Join(“.”,propertyPath);
}
private static string GetPropertyPath<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
{
var propertyPath = new Stack<string>();
var body = (MemberExpression)expression.Body;
do
{
propertyPath.Push(body.Member.Name);
// this will evaluate to null when we will reach ParameterExpression (x in "x => x.Foo.Bar....")
body = body.Expression as MemberExpression;
}
while (body != null);
return string.Join(".", propertyPath);
}