c# - 为什么 Razor 不喜欢这个?

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

我有一个非常烦人的问题,我认为:

@{

        if(ViewBag.Section == "Home")
        {
           <div id="headerfrontPage">   
        }
        else
        {
            <div id="header">   
        }


     }

我得到一个编译错误:

The code block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.

如何有条件地编写一个 div?它基本上是为了黑客...

最佳答案

当你包裹你的 div 的内部元素时,你可以使用相同的结构,比如:

@if (ViewBag.Section == "Home")
{
    <text><div id="headerfrontPage"></text>
}
else
{
    <text><div id="header"></text>
}

或者你使用razor语法@: like

@if (ViewBag.Section == "Home")
{
    @:<div id="headerfrontPage">
}
else
{
    @:<div id="header">
}

但对于您目前的情况,我更喜欢 Ron Sijm 的解决方案:

@{
var divName = ViewBag.Section == "Home" ? "headerfrontPage" : "header";
}

<div id="@divName"> 

关于c# - 为什么 Razor 不喜欢这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8040482/

相关文章:

angularjs - 使用 Angular JS 在 ASP .Net MVC 中进行表单验证

c# - 如何从 IQueryable 变量中获取数据字段?

c# - 使用 NEST Field Boosting 的 Elasticsearch

deployment - 初始化字符串的格式不符合从索引0开始的规范

asp-classic - IIS Express 是否支持调试经典 ASP?

html - 在超小屏幕上将文本对齐从右更改为左

C# - 检查是否设置了整数属性

c# - 通过密码学生成唯一编号

asp.net - 在 _LogonPartial 中显示模型数据

C# MVC3 Razor 在@foreach 列表中交替项目?