Reputation: 5105
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???
Upvotes: 14
Views: 28148
Reputation: 11
If you don't have a requirement to use DisplayFor
, here is the syntax to join different strings in .cshtml files:
@($"{User.FirstName} {User.MiddleName} {User.LastName}")
Upvotes: 1
Reputation: 71
@Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName)
Upvotes: 7
Reputation: 26940
You can do this:
@foreach (var item in Model.FormNotes) {
var conc = item.User.FirstName + item.User.LastName;
<tr>
<td>
@Html.Display(conc)
</td>
</tr>
}
Or it would be better solution to have property FullName in model
Upvotes: 3
Reputation: 33149
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);
Upvotes: 19