Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3 Razor Concatenate String

I have the following in my ASP.Net MVC 3 Razor View

@foreach (var item in Model.FormNotes) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.User.firstName)
    </td>
</tr>
}

Which works fine, however, I would like to concatenate the string to display both the firstName and lastName, but when I try to do this

<td>
  @Html.DisplayFor(modelItem => item.User.firstName + @item.User.lastName)
</td>

I get the following error

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

Does anyone know how to concatenate a string in a Razor View?

Thanks all.

EDIT

My Razor View accepts a ViewModel which looks like this

public class ViewModelFormNoteList
{
    public IList<Note> FormNotes { get; set; }
}

I would like to put the FullName property in here, as suggested by Roy, however, I am not sure how to get it working???

like image 599
tcode Avatar asked May 29 '12 10:05

tcode


1 Answers

DisplayFor needs a property to map to, so a concatenation is impossible. You might expose a read-only property FullName on your model, which then returns the concatenation:

public string FullName
{
   get
   {
      return User.FirstName + " " + User.LastName;
   }
}

and then use that in your DisplayFor.

@Html.DisplayFor(modelItem => modelItem.FullName);
like image 56
Roy Dictus Avatar answered Oct 05 '22 20:10

Roy Dictus