Altering expression
I have a very short question. In mvc there is a static extension method
System.Web.Mvc.Html.InputExtensions.HiddenFor(this HtmlHelper<TModel>htmlhelper,Expression<Func<TModel,TProperty>> expression,object htmlAttributes)
I`m using this method to create DropDownList based on HiddenField.
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;
}
And as for simple type property it is easy to create such HiddenFields. In view i use it like this:
@Html.CreateDropDown(t=>t.SelectedValue,(some items list),(some attributes)) // t.SelectedValue is property of type string
But now i want to create many hidden fields based on property that implements IList interface. The function should look like this:
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.ToRouteValueDi开发者_开发百科ctionary(new { @class = "DropDownInputHidden" })));
}
//some other code...
return MvcHtmlString.Create(resultVar.ToString());
}
and after that i should been able to call this modified funcion like this:
@Html.CreateDropDown(t=>t.SelectedManyValues,(some items list),(some attributes)) // t.SelectedManyValuesis property of type List<string>
So what i need is to modify somehow the expression to get each value from the expression.
Anyone have some ideas?
This is what I would do in your situation, since you already have developed CreateDropDown and might want to reuse that code.
Create a partial view called String.cshtml
in Shared/DisplayTemplates
The contents of that view should be something like:
@model System.String
@Html.CreateDropDown(x => x, (some items list), (some attributes))
After that, in the main view, you can just do:
@Html.DisplayFor(t => t.SelectedManyValues, (some items list), (some attributes))
Let me know if that works for you!!!
精彩评论