这是我的任何字典的 Html 助手:
public static IHtmlString DictionaryFor<TModel, TKey, TValue>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, IDictionary<TKey, TValue>>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IDictionary<TKey, TValue> dictionary = (IDictionary<TKey, TValue>)metaData.Model;
StringBuilder resultSB = new StringBuilder();
int i = 0;
foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
{
MvcHtmlString hiddenKey = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Key", kvp.Key.ToString());
MvcHtmlString hiddenValue = htmlHelper.Hidden($"{metaData.PropertyName}[{i}].Value", kvp.Value.ToString());
resultSB.Append(hiddenKey.ToHtmlString());
resultSB.Append(hiddenValue.ToHtmlString());
i++;
}
return MvcHtmlString.Create(resultSB.ToString());
}
在这样的视图中调用它:
@Html.DictionaryFor(model => model.AnyDictionary)