【问题标题】:How to concatenate variables in razor?如何在剃刀中连接变量?
【发布时间】:2015-03-10 06:13:14
【问题描述】:

我想连接从数据库中获取的用户个人资料的“姓名”和“姓氏”。我在 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>
}

但是,在运行站点并成功登录后,出现以下错误: 只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句

我可以通过更改这行代码来解决这个问题:

@currentUser.Name @currentUser.LastName;

这将正确显示姓名和姓氏,但它们之间没有空格。

任何线索如何解决这个问题? 问候!

【问题讨论】:

  • @currentUser.Name &amp;nbsp@currentUser.LastName;?

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor


【解决方案1】:

无需使用@登录赋值运算符试试如下:

@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>
}

或者像这样使用它:

@currentUser.Name &nbsp; @currentUser.LastName

【讨论】:

    【解决方案2】:
     @{
       string str1="Hello";
       string str2=" World";
      }
    

    你可以如下连接

    纯 HTML

     @str1 @str2
    

    内部代码块

     @{
       string str3=str1+str2;
      }
    

    内联

    @(str1+str2)
    

    【讨论】:

      【解决方案3】:

      删除';'

      @currentUser.Name @currentUser.LastName
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 2012-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 2015-04-03
        相关资源
        最近更新 更多