Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditorFor HTML Helper with knockout

I was thinking it would be very useful to have an extended version of the EditorFor HTML helper which automatically writes out value data bindings for Knockout JS.

This would be for where the client side view model and the server side view model are the same - I've already autogenerated the client side view model by using ko mapping and getting the viewmodel via AJAX.

Has anyone else attempted something like this, or are there any projects which include something similar to what I'm thinking here?

The advantage of this would be that when refactoring there would be no danger of the data bound values being missed.

like image 293
Chris Nevill Avatar asked Oct 04 '22 15:10

Chris Nevill


1 Answers

We have done something along these lines, its far from perfect, and we have much more in our custom extensions, but I extracted the essence.

using System.Web.Mvc.Html;

namespace System.Web.Mvc
{
    public static class EditorForExtensions
    {
        public static MvcHtmlString TextBoxForViewModel<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            var htmlAttributes = HtmlAttributesForKnockout(metadata);

            return htmlHelper.TextBoxFor(expression, htmlAttributes);
        }

       private static Dictionary<string, object> HtmlAttributesForKnockout(ModelMetadata metadata)
        {
            var htmlAttributes = new Dictionary<string, object>();

            var knockoutParameter = String.Format("value: {0}", metadata.PropertyName);

            htmlAttributes.Add("data-bind", knockoutParameter);

            return htmlAttributes;
        }
    }
}

This can then be used like:

@Html.TextBoxForViewModel(m => m.Name)
like image 129
Chad Edrupt Avatar answered Oct 13 '22 11:10

Chad Edrupt