Razor - how to render content into a variable

后端 未结 4 652
北恋
北恋 2021-01-04 01:29

How to render a piece of Html into a variable in Razor? In Spark I used to write the following code:


    

        
4条回答
  •  礼貌的吻别
    2021-01-04 01:51

    Basically the OP already answered the problem in that you could do something like:

    @{
       Func a = @
           Some Text        
       ;
       @a(new object())
    }    
    

    If the text is for a single line only you could even use the "@:" operator, just remmebr to have a semicolon (or if it needs any closing brackets or parenthesis) on the next line, as in the following example:

    @{
       Func a = @: Some Text
       ;    
       @a(new object())
    }
    

    However you can capture it directly as a string if you want

    @{
        string a = ((Func)(@
                        Some Text
                    ))("").ToString();
        @a //Output directly as a string        
    }
    

    You could even encapsulate it in a function:

    @functions{
         public string ToString(Func input)
         {
              return input("").ToString();
         }
    }
    
    @{
        string a = ToString(@
                        Some Text
                   );
        @a //Output directly as a string        
     }
    

提交回复
热议问题