Search code examples
htmlasp.net-mvcvisual-studiorazorrazor-declarative-helpers

How can we reference an HTML markup element in an MVC Razor View


Using MVC Razor how can we reference an HTML markup element in our view as a template (that can be passed to a helper as a string or object)?

Example of desired functionality (or similar, I prefer a/the standardized approach but I haven't been able to find one):

@TemplateOne {
    <!--Standard Razor markup:-->
    <div>
        <p>@Model.Summary</p>
        <table>
            <tr>
                <td>Lorem ispum...</td>
            </tr>
        </table>
    </div>
}

Reference by ID:

@{
    var templateToPassToHelper = TemplateOne;
}

I know that the syntax on the above code is incorrect because its not working on my local tests. The closest I've come to accomplishing this is to use the following (which doesn't answer the question or fix the issue because the variable is just a string and using this approach keeps the dev from being able to use the Visual Studio intellisense and other HTML editing assistance):

string template =
  @"<html>
      <head>
        <title>Hello @Model.Name</title>
      </head>
      <body>
        Email: @Html.TextBoxFor(m => m.Email)
      </body>
    </html>";

Solution

  • There are a couple ways you can do what you are talking about.

    Going off of @brent-mannering comment:

    Create a razor partial file (_partial.cshtml):

    <div>
        <p>@Model.Summary</p>
        <table>
            <tr>
                <td>Lorem ispum...</td>
            </tr>
        </table>
    </div>
    

    And then use @Html.Partial("_partial.cshtml",Model) in wherever you want the template.

    Or you could use a helper function:

    @helper TemplateOne(){
        <div>
            <p>@Model.Summary</p>
            <table>
                <tr>
                    <td>Lorem ispum...</td>
                </tr>
            </table>
        </div>
    }
    <!--body of your page-->
    @TemplateOne()