Why does Razor not like this?

后端 未结 5 1440
闹比i
闹比i 2020-12-18 20:32

Ive got a mega annoying problem I have a view with:

@{

        if(ViewBag.Section == \"Home\")
        {
           
相关标签:
5条回答
  • 2020-12-18 20:54

    I suspect it is because your divs are not closed, so razor assumes that the closing brace is actually part of the div content.

    You might try outputting the entire div content within your code there, including the closing tag, or output the div tag with a Response.Write, or something similar, so there is no confusing markup.

    EDIT: also, maybe enclosing your div tag in a

    <text></text>
    

    might be worth a try.

    0 讨论(0)
  • 2020-12-18 20:55

    The simplest way to write this would be:

    <div id="@(ViewBag.Section == "Home" ? "headerFrontPage" : "header")">
    

    Or, if you prefer, you can use a local variable:

    @{ var headerID = ViewBag.Section == "Home" ? "headerFrontPage" : "header"; }
    
    <div id="@headerID">
    

    Regarding the more general case of unclosed tags in Razor code blocks, you can explicitly mark the opening tag as content:

    @if (ViewBag.Section == "Home")
    {
        @:<div id="headerFrontPage">
    }
    else
    {
        @:<div id="header">
    }
    
    0 讨论(0)
  • 2020-12-18 20:58

    Try this:

    @if (ViewBag.Section == "Home")
    {
        <text> <div id="headerfrontPage"> </text>
    }
    else
    {
        <text> <div id="header"> </text>
    }
    
    0 讨论(0)
  • 2020-12-18 21:00

    You can use the same construct when you wrap your div's inside element like:

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

    Or you use razor syntax @: like

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

    But for your current situation I would prefer Ron Sijm's solution:

    @{
    var divName = ViewBag.Section == "Home" ? "headerfrontPage" : "header";
    }
    
    <div id="@divName"> 
    
    0 讨论(0)
  • 2020-12-18 21:11

    You could try this:

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

    I'm not sure if that will help, it a long shot. But at least imo that looks better...

    0 讨论(0)
提交回复
热议问题