سؤال

I want to render dynamic HTML content into a variable to later pass it to a function. The reason is, that I receive the actual content through another platform and I can print it out using an internal function. This function accepts values to put into placeholders.

Example:

This is my content:
{mytable}
Blah

Now I can set any content on mytable. Good. The content I want to put there is currently the following.

@using System.Data
@model Dictionary<string, DataView>
<table>
    @foreach (var group in Model)
    {
        <tr>
            <th colspan="3">@group.Key</th>
        </tr>

        foreach (DataRowView data in group.Value)
        {
            <tr>
                <td>@data.Row["col1"]</td>
                <td>@data.Row["col2"]</td>
                <td>@data.Row["col3"]</td>
            </tr>
        }
    }
</table>

Well. What is the best way to actually render the above output into a variable? I firstly thought of just appending every HTML line into a string, but it sounds rather inefficient and weak to me.

I'm not an expert in ASP.NET, I come from PHP and I know a bit about output buffers. Is this a possible way? What would you recommend?

هل كانت مفيدة؟

المحلول

You could create a ViewHelper:

@helper RenderTable(Dictionary<string, System.Data.DataView> model)
{
    <table>
        @foreach (var group in Model)
        {
            <tr>
                <th colspan="3">@group.Key</th>
            </tr>

            foreach (System.Data.DataRowView data in group.Value)
            {
                <tr>
                    <td>@data.Row["col1"]</td>
                    <td>@data.Row["col2"]</td>
                    <td>@data.Row["col3"]</td>
                </tr>
            }
        }
    </table>
}

Then call it:

@{
    string output = RenderTable(someData).ToHtmlString();
}

نصائح أخرى

Create strongly typed partial view and add this partial view in actual view

See below link

http://www.codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top