改变表达方式

时间:2011-09-13 15:39:11

标签: asp.net-mvc lambda c#-3.0 html-helper expression-trees

我的问题非常简短。 在mvc中有一个静态扩展方法

System.Web.Mvc.Html.InputExtensions.HiddenFor(this HtmlHelper<TModel>htmlhelper,Expression<Func<TModel,TProperty>> expression,object htmlAttributes)

我正在使用此方法基于HiddenField创建DropDownList。

 public static MvcHtmlString CreateDropDown<TModel, TProperty, TKey, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ObjectData<TKey, TValue>> items, object htmlAttributes)
    {
            var resultVar = System.Web.Mvc.Html.InputExtensions.HiddenFor(helper, expression, htmlAttributes.ToRouteValueDictionary(new { @class = "DropDownInputHidden" }));
            //some other code...
            return resultVar;
    }

至于简单类型属性,很容易创建这样的HiddenFields。在视图中我使用它像这样:

@Html.CreateDropDown(t=>t.SelectedValue,(some items list),(some attributes)) // t.SelectedValue is property of type string

但是现在我想基于实现IList接口的属性创建许多隐藏字段。该函数应如下所示:

    public static MvcHtmlString CreateDropDown<TModel, TProperty, TKey, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<ObjectData<TKey, TValue>> items, object htmlAttributes)
    {
            StringBuilder resultVar =new StringBuilder();
            for (int i = 0; i < items.Count(); i++)
            {
                Expression<Func<TModel,TProperty>> ExpressionThatWillPointTo_i_Element = ???; 
                //ExpressionThatWillPointTo should be "based" on expression that is "pointing" to List<string>;
                resultVar.Append(System.Web.Mvc.Html.InputExtensions.HiddenFor(helper, ExpressionThatWillPointTo_i_Element, htmlAttributes.ToRouteValueDictionary(new { @class = "DropDownInputHidden" })));
            }
            //some other code...
            return MvcHtmlString.Create(resultVar.ToString());
    }

之后我应该能够像这样调用这个修改过的函数:

@Html.CreateDropDown(t=>t.SelectedManyValues,(some items list),(some attributes)) // t.SelectedManyValuesis property of type List<string>

所以我需要的是以某种方式修改表达式以从表达式中获取每个值。

任何人都有一些想法?

1 个答案:

答案 0 :(得分:0)

这就是我在你的情况下会做的事情,因为你已经开发了CreateDropDown并且可能想要重用那段代码。

String.cshtml

中创建名为Shared/DisplayTemplates的部分视图

该视图的内容应该类似于:

@model System.String

@Html.CreateDropDown(x => x, (some items list), (some attributes))

之后,在主视图中,您可以这样做:

@Html.DisplayFor(t => t.SelectedManyValues, (some items list), (some attributes))

让我知道这是否适合你!!!

相关问题