MikePR
MikePR

Reputation: 2986

How to concatenate variables in razor?

I would like to concatenate the 'Name' and 'LastName' of the user profile that I fetch from the database. I have the following code in Razor:

@if (Request.IsAuthenticated)
{
  var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
  var currentUser = manager.FindById(User.Identity.GetUserId());
  var fullName = @currentUser.Name + " " + @currentUser.LastName;
  @fullName;
}
else
{
  <span>Guess</span>
}

However, when running the site and after log in successfully I got the following error: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

I can fix this changing this line of code:

@currentUser.Name @currentUser.LastName;

This will displayed the Name and Last Name correctly but without the space between them.

Any clue how to solve this? Regards!

Upvotes: 0

Views: 5177

Answers (3)

Spider man
Spider man

Reputation: 3330

remove ';'

@currentUser.Name @currentUser.LastName

Upvotes: 0

Bellash
Bellash

Reputation: 8184

 @{
   string str1="Hello";
   string str2=" World";
  }

You may concatenate as follows

Plain HTML

 @str1 @str2

Inside code block

 @{
   string str3=str1+str2;
  }

Inline

@(str1+str2)

Upvotes: 0

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

No need to use @ sign in assignment operator try something like below:

@if (Request.IsAuthenticated)
{
  var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
  var currentUser = manager.FindById(User.Identity.GetUserId());
  var fullName = currentUser.Name + " " + currentUser.LastName;
  @fullName;
}
else
{
  <span>Guess</span>
}

Or use it like this:

@currentUser.Name &nbsp; @currentUser.LastName

Upvotes: 2

Related Questions