Search code examples
asp.net-mvcrazor

Having ASP.NET MVC partial view without creating a new file


Is there a way to have the partial view code directly inside the main view? I got code in a view that is repeating but I don't want to create a new file for the partial view. I could see it work like a section

@inlineview Test {
   <b>Some Text</b>
}

@RenderInlineView("Test")
...
@RenderInlineView("Test")
...
@RenderInlineView("Test")

Solution

  • If you have a block of code (incl. HTML) you want to reuse, you can use Razor helpers.

    @Test()
    
    @Test()
    
    // Helpers
    @helper Test(){
        <b>Some Text</b>
    }
    

    Would result in

        <b>Some Text</b>
    
        <b>Some Text</b>