Render HTML from lambda to MVC

I have the following code to create a list and will allow developers to customize the output, if necessary.

<% Html.List<MyList>(item => item.Property).Value(item => return "<div>" + item.Property + "<br/>" + item.AnotherProperty + "</div>").Render() %>

This is not ideal, as I can allow developers to add html similar to other controls.

<% Html.List<MyList>(item => item.Property).Value(item => %> <div><%=item.Property%><br/><%=item.AnotherProperty%></div><%).Render() %>

This method is much cleaner and more standard with the rest of mvc.

+3
source share
1 answer

The <% =%> tags are just a shortcut to Response.Write. If you think about it, the lambda expression just allows you to delay the execution of the Response.Write code until the appropriate time.

, - Response.Write , , lambda, Response.Write, .

, :

public class TableBuilder
{
    private Action<int> _template;

    public TableBuilder Template(Action<int> template)
    {
        _template = template;
        return this;
    }

    public void Render()
    {
        var r = HttpContext.Current.Response;

        r.Write("<table>");

        for(int i=0; i<10; ++i)
        {
            r.Write("<tr><td>");
            if(_template != null)
            {
                _template(i);
            }
            r.Write("</td></tr>");
        }

        r.Write("</table>");
    }
}

, , :

<body>
    <div>
    <% Html.TableBuilder().Template(i => { %>

                                          <%= i %>: I'm a template

                        <% }).Render(); %>
    </div>
</body>

!

+2

Source: https://habr.com/ru/post/1742350/


All Articles