【发布时间】:2016-10-13 15:53:34
【问题描述】:
我正在尝试为 ASP.NET MVC5 实现一个类似于 Html.HiddenFor 的 HTML-Helper 方法,但我想传递一个 IList<T> 并让它为每个人调用 Html.HiddenFor。
这是我目前得到的:
public static void HiddenForEach<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IList<TProperty>>> expression)
{
IList<TProperty> allItems = expression.Compile().Invoke(htmlHelper.ViewData.Model);
for (int i = 0; i < allItems.Count; ++i)
{
var withIndex = Expression.Lambda<Func<TModel, TProperty>>(...??...);
htmlHelper.ViewContext.Writer.Write(htmlHelper.HiddenFor<TModel, TProperty>(withIndex).ToHtmlString());
}
}
我正在调用表达式来获取 IList,然后,我正在遍历其中的所有项目。
但是,我不知道如何构建表达式来访问IList 中的一个特定元素,即如何构建表达式以获得与Html.HiddenFor(m => m.ListOfSomething[0])、Html.HiddenFor(m => m.ListOfSomething[1]) 等价的东西。
此外,我不确定是否应该使用 htmlHelper.ViewContext.Writer 来输出生成的 HTML 或者以某种方式连接 MvcHtmlStrings 并返回它们?
【问题讨论】:
-
如果你去挖掘源代码,你可以看到他们是如何为
HiddenFor做的,并了解你想要做什么。 aspnetwebstack.codeplex.com/SourceControl/changeset/view/…
标签: c# asp.net-mvc razor lambda asp.net-mvc-5