Is there an easy way to do a recursive HiddenFor?
I want something like EditorFor which will generate a form for each property pointed to by the expression. The current behavior is to generate a single hidden input and use the ToString() value as the value. I would like to create a set of hidden inputs one for each property. If the value is not a primitive value then that in turn should be broken down into multiple hidden inputs. This allows a model to be passed from one action to another.
I wrote a helper to do it but it seems like something that should just be there already. Here is the helper in case anyone else finds it useful.
public static MvcHtmlString MultipleHiddenFor<TModel, TProperty>
(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
return MultipleHiddenHelper(helper, metadata, ExpressionHelper.GetExpressionText(expression));
}
private static MvcHtmlString MultipleHiddenHelper<TModel>(HtmlHelper<TModel> helper, ModelMetadata metadata, string expression)
{
var bldr = new StringBuilder();
foreach (var value in metadata.Properties)
{
var propexpression = expression + "." + value.PropertyName;
if (value.IsComplexType)
{
var propmetadata = ModelMetadata.FromStrin开发者_JAVA百科gExpression(propexpression, helper.ViewData);
bldr.Append(MultipleHiddenHelper(helper, propmetadata, propexpression));
}
else
{
bldr.Append(helper.Hidden(helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(propexpression),
value.Model));
}
}
return new MvcHtmlString(bldr.ToString());
}
I don't think this is a bad solution but you should be aware that if you're completely outputting an object like you're doing (probably some database related object) you're leaving yourself open to having these elements hijacked.
By that I mean someone could change the value of these hidden fields (which you don't want to be edited anyway) and potentially be updated or inserted into the database, changing things you did not intend.
精彩评论