"Templates Can Be Used Only with Field Access, Property Access, Single-Dimension Array Index, or Single-Parameter Custom Indexer Expressions" Error

Templates can be used only with field access, property access, single-dimension array index error

You can't use DisplayFor because the expression can't leverage that extension method, you just use the raw value:

@objclasstime.ReturnPersianDay(int.Parse(item.ClassDay))

instead of:

@Html.DisplayFor(modelItem => objclasstime.ReturnPersianDay(int.Parse(item.ClassDay)))

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions

You could make your helper a little more generic and get rid of the object argument:

public static MvcHtmlString MyEditFor<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> expression
)
{
var partial = html.Partial(
"Item",
new LabelEditorValidation
{
Label = html.LabelFor(expression),
Editor = html.EditorFor(expression),
Validation = html.ValidationMessageFor(expression)
}
).ToString();
return MvcHtmlString.Create(partial);
}

Now your expression won't break as there won't be unnecessary boxing.

Templates can be used only for field access

Try:

Html.DisplayFor(y => y.Data.Select(z => z.Name).First().ToString())

That Will Show The Value Instead of the property name.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions

I find a solition for this problem.

I use PropertyInfo

I add exdent method on Expression<Func<T, dynamic>>

public static PropertyInfo GetProperty<T>(this Expression<Func<T, dynamic>> expression)
{
MemberExpression memberExpression = null;

if (expression.Body.NodeType == ExpressionType.Convert)
{
memberExpression = ((UnaryExpression)expression.Body).Operand as MemberExpression;
}
else if (expression.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpression = expression.Body as MemberExpression;
}

if (memberExpression == null)
{
throw new ArgumentException("Not a member access", "expression");
}

return memberExpression.Member as PropertyInfo;
}

and change this line

ModelMetadata metadata = ModelMetadata.FromLambdaExpression<T, object>(ColumnProperty, pHtml.ViewData);

to

PropertyInfo pi = FieldProperty.GetProperty<T>();

I can access need all attributes and properties on PropertyInfo

formatting DateTime error Templates can be used only with field access, property access, single-dimension array index..

DisplayFor expects an expression that identifies the object that contains the properties to display. It will use built in, or custom, templates to render that display. You trying to provide the display logic as that expression parameter, which is not valid.

Use

@String.Format("HH:mm:ss", Model.row.LastUpdateDate)

or

@Model.row.LastUpdateDate.ToString("HH:mm:ss")


Related Topics



Leave a reply



Submit