@Html.HiddenFor does not work on Lists in ASP.NET MVC

后端 未结 13 846
灰色年华
灰色年华 2020-11-27 15:13

I\'m using a model that contains a List as a property. I\'m populating this list with items i grab from SQL Server. I want the List to be hidden in the view and passed to th

相关标签:
13条回答
  • 2020-11-27 15:56

    maybe late, but i created extension method for hidden fields from collection (with simple data type items):

    So here it is:

    /// <summary>
    /// Returns an HTML hidden input element for each item in the object's property (collection) that is represented by the specified expression.
    /// </summary>
    public static IHtmlString HiddenForCollection<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression) where TProperty : ICollection
    {
        var model = html.ViewData.Model;
        var property = model != null
                    ? expression.Compile().Invoke(model)
                    : default(TProperty);
    
        var result = new StringBuilder();
        if (property != null && property.Count > 0)
        {
            for(int i = 0; i < property.Count; i++)
            {
                var modelExp = expression.Parameters.First();
                var propertyExp = expression.Body;
                var itemExp = Expression.ArrayIndex(propertyExp, Expression.Constant(i));
    
                var itemExpression = Expression.Lambda<Func<TModel, object>>(itemExp, modelExp);
    
                result.AppendLine(html.HiddenFor(itemExpression).ToString());
            }
        }
    
        return new MvcHtmlString(result.ToString());
    }
    

    Usage is as simple as:

    @Html.HiddenForCollection(m => m.MyList)
    
    0 讨论(0)
提交回复
热议问题