ASP.Net MVC 3 Razor Concatenate String
Asked Answered
C

4

14

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???

Cyclopedia answered 29/5, 2012 at 10:58 Comment(1)
tg - as per your edit, you'd have to amend your Note class as per Roy's suggestion, then it would all work without further change (other than of course the @Html.DisplayFor(modelItem => modelItem.FullName) part :)) if it's not possible to change the Note class, then you may have to create a mapping class which includes the concatenation property and then use that in your ViewModelFormNoteList classGiana
G
19

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);
Gob answered 29/5, 2012 at 11:1 Comment(4)
I like your solution, however, I am not sure if it will work with my ViewModel class, please look at my Updated Question. Thanks.Cyclopedia
right solution is to have concatenation in view, because it's view's part of jobDominic
DisplayFor is a helper method for use in Views exclusively. So the solution here is perfectly fine.Gob
Great solution!Coruscation
K
7
 @Html.DisplayFor(modelItem => item.FirstName) @Html.DisplayFor(modelItem => item.LastName)
Ketosis answered 4/4, 2013 at 7:16 Comment(0)
O
3

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

Oviparous answered 29/5, 2012 at 11:3 Comment(0)
C
1

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}")
Calve answered 27/7, 2020 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.