using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Text.RegularExpressions; namespace Sleis.HtmlHelpers { public static class ListModelBindingExtensions { static Regex _stripIndexerRegex = new Regex(@"\[(?\d+)\]", RegexOptions.Compiled); public static string GetIndexerFieldName(this TemplateInfo templateInfo) { string fieldName = templateInfo.GetFullHtmlFieldName("Index"); fieldName = _stripIndexerRegex.Replace(fieldName, string.Empty); if (fieldName.StartsWith(".")) { fieldName = fieldName.Substring(1); } return fieldName; } public static int GetIndex(this TemplateInfo templateInfo) { string fieldName = templateInfo.GetFullHtmlFieldName("Index"); var match = _stripIndexerRegex.Match(fieldName); if (match.Success) { return int.Parse(match.Groups["index"].Value); } return 0; } public static MvcHtmlString HiddenIndexerInputForModel(this HtmlHelper html) { string name = html.ViewData.TemplateInfo.GetIndexerFieldName(); object value = html.ViewData.TemplateInfo.GetIndex(); string markup = String.Format(@"", name, value); return MvcHtmlString.Create(markup); } public static MvcHtmlString HiddenIndexerInputForModel(this HtmlHelper html, object index) { string name = html.ViewData.TemplateInfo.GetIndexerFieldName(); object value = index; string markup = String.Format(@"", name, value); return MvcHtmlString.Create(markup); } } }