【问题标题】:Razor Inline code generating Compiler ErrorRazor 内联代码生成编译器错误
【发布时间】:2014-01-29 16:00:53
【问题描述】:

我正在尝试使用 KendoGrid 内容模板和内联 Razor 动态设置单元格的内容,但我遇到了各种错误。

"<table><tr>" + 
"<td style='color:yellow; width:200px;height:13px;padding-top:0px; margin-top:0px;text-align:center;' class='audiogrid'>" +
@{
   @if ((int)TempData["MediaTypeId"] == 1) { 
      @"<audio id='a1' src='#: MediaLocation #' controls='controls' preload='auto' autobuffer><embed height='26' autostart = 'false' type = 'audio/mpeg' width='290' src='#: MediaLocation #'></audio>" +
   }
   else{
     @"&nbsp; #: Description # " +
   }
}
"</td>" +
"</tr></table>"

上面的代码抛出一个错误:CS1646: Keyword, identifier, or string expected after verbatim specifier: @ at the first instance of the @ sign.

我不明白这个错误的原因或含义。根据在 MVC4 中使用 Razor 的规则,我的语法应该可以工作。做了一些研究以确定并发现语法是准确的here 但我尝试了一个变体,在 @ 之后包含一个字符串,正如错误所建议的那样,我认为它应该也可以工作:

"<table><tr>" + 
"<td style='color:yellow; width:200px;height:13px;padding-top:0px; margin-top:0px;text-align:center;' class='audiogrid'>" +
@if ((int)TempData["MediaTypeId"] == 1) { 
    @"<audio id='a1' src='#: MediaLocation #' controls='controls' preload='auto' autobuffer><embed height='26' autostart = 'false' type = 'audio/mpeg' width='290' src='#: MediaLocation #'></audio>" +
    }
    else{
          @"&nbsp; #: Description # " +
    }
"</td>" +
"</tr></table>" 

这一次我收到编译器错误消息:CS1026:) 预期在 @ 首次出现在我的代码中的同一行。

我也尝试了一些其他的变体,但似乎都不起作用。 我在这里做错了什么或错过了什么? :-(

基本上单元格中的控件应该根据媒体类型而改变。

【问题讨论】:

    标签: asp.net-mvc-4 razor


    【解决方案1】:

    Razor 不是某种字符串连接语法。您指定 html 标记和 C# 代码,Razor 引擎将它们写入客户端。

    @{ 块(或任何其他代码块)内,您可以使用 C# 语句。不需要额外的@。

    @if(或任何其他代码块)内,您可以使用html 标签。无需在它们前面加上@。

    else块内,使用@:输出不带html标签的html。

    <table><tr>
    <td style='color:yellow; width:200px;height:13px;padding-top:0px; margin-top:0px;text-align:center;' class='audiogrid'>
    @{
       if ((int)TempData["MediaTypeId"] == 1) { 
          <audio id='a1' src='#: MediaLocation #' controls='controls' preload='auto' autobuffer><embed height='26' autostart = 'false' type = 'audio/mpeg' width='290' src='#: MediaLocation #'></audio>
       }
       else{
          <text>&nbsp; #: Description # </text>
       }
    }
    

    【讨论】:

    • 感谢GyS的启迪。代码块中的 @ 是我试图确定错误含义的徒劳尝试。我根据您的建议修改了我的代码,不再收到任何其他错误,但现在收到“解析器错误消息:内联标记块 (@

      Content

      ) 无法嵌套。只有一层内联标记被允许。”在 else 块中使用 @: 任何想法这意味着什么?我理解您对其使用的解释,但该错误对我来说没有意义
    • 看看这里:aspnetwiki.com/… 看起来你的嵌套标签像
    • 如果我不是很明显。但我肯定会尝试您链接中提供的替代方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多