.

writing HtmlExtensions

The following is an example of how to write a Html Extension

This particular example is to build a foreach loop for Knockout.

the Html Extension:

public static class HtmlExtensions
{
    public static KoForeach<TModel, TProperty> KoForeach<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
    {
        return new KoForeach<TModel, TProperty>(htmlHelper, htmlAttributes);
    }
}

The tag class (seperate class so that on disposal, it will fire the closing tag)

public class KoForeach<TModel, TProperty> : IDisposable
{
    private readonly HtmlHelper<TModel> _helper;

    public KoForeach(HtmlHelper<TModel> helper, object htmlAttributes = null)
    {
        _helper = helper;
        var attrs = new StringBuilder();

        if (htmlAttributes != null)
        {
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
            {
                attrs.Append(string.Format(" {0}={1}", property.Name, property.GetValue(htmlAttributes)));
            }
        }

        _helper.ViewContext.Writer.Write(string.Format("<!-- ko foreach: {0} -->", "names"));
    }

    public IHtmlString Item(string item)
    {
        return new HtmlString(string.Format("<li>{0}</li>", item));
    }

    public void Dispose()
    {
        _helper.ViewContext.Writer.Write("<!-- /ko -->");
    }
}

usage:

@using (Html.KoForeach(myvm => myvm.names))
{
    <input type="text" data-bind="value: $data"/>
}

script:

<script type="text/javascript">
    var viewModelName = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
//this relies on: @*<script src="~/Scripts/knockout.mapping-latest.js"></script>*@
    console.log(viewModel.names());
    ko.applyBindings(viewModel);
</script>

What's your thoughts on this?

*

Protected by WP Anti Spam