Razor - how to render content into a variable

后端 未结 4 748
北恋
北恋 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条回答
  •  旧时难觅i
    2021-01-04 01:49

    Just in case anyone else finds this post (as I did), Andy's Update is almost there. In addition to the example given, all you have to do to access the 'int' in the example given is reference @item. In @ blocks, the variable item contains the model it was called on.

    Here's an example of how it can be used:

    @model PageData
    
    @{
        Func sayHi = 
            @
                 
  • Hello @(item.FirstName)!
  • ; }
      @foreach(var customer in Model.Customers) { sayHi(customer); }

    In most instances you should probably use a partial view instead of a function like this. But in the rare instances that a partial view is not possible (such as when using the RazorEngine library), this works.

提交回复
热议问题