Wednesday, 6 March 2013

Getting the Error: "Templates Can be used only with field access,property access, single dimension, or Single-parameter Custom Indexer Expression" in Asp.Net MVC3/MVC4



While working on an MVC3 project I need to Show the short date  & time in the display for HTML helper, but when I used it is throwing the above error, the reason behind it was that the HTML helper DisplayFor and EditorFor  takes directly the properties of the model rather than the functions which are associated with it.
  @Html.DisplayFor(model => model.DateStart.Value.ToShortDateString( ))

To fix the above situation you can simply remove the DisplayFor and use as :

@if(Model.DateStart!=null)
{
  Model.DateStart.ToShortDate( )
}


However, the best method to fix this situation is create a partial class with the above field and use the DisplayFormat properties to it with the one you wants.

    [DisplayName("Start Date")]
    [DisplayFormat(DataFormatString="{0:MM/dd/yyyy}",  ApplyFormatInEditMode=true)]
    public System.Nullable<System.DateTime> ModifiedStartDate
    {
        get
        {
            return this.StartDate.ToShortDateString( );
        }
        set
        {
            this.StartDate = value;
        }
    }


How to use it:
  @Html.DisplayFor(model => model.ModifiedStartDate)