在View </string>中创建HiddenFor IEnumerable <string>

时间:2012-10-19 20:28:18

标签: c# asp.net-mvc asp.net-mvc-3 linq entity

我有一个属于IEnumerable的属性

public IEnumerable<string> ChangesOthersResult { get; set; }

我需要从ChangesOthersResult收集所有值,并从视图发回到控制器。如何遍历Ienumerable并创建将绑定回控制器中的ViewModel的隐藏字段?

foreach(var item in Model.ChangesOthersResult)
   {
       @Html.HiddenFor(x => x.ChangesOthersResult);
   }

将Raw SQL语句作为文本提供给我。

7 个答案:

答案 0 :(得分:19)

我把它变成了一个扩展方法,所以for循环不会破坏你的视图代码:

public static class HiddenExtensions
{
    public static MvcHtmlString HiddenForEnumerable<TModel, TProperty>(this HtmlHelper<TModel> helper,
        Expression<Func<TModel, IEnumerable<TProperty>>> expression)

    {
        var sb = new StringBuilder();

        var membername = expression.GetMemberName();
        var model = helper.ViewData.Model;
        var list = expression.Compile()(model);

        for (var i = 0; i < list.Count(); i++)
        {
            sb.Append(helper.Hidden(string.Format("{0}[{1}]", membername, i), list.ElementAt(i)));
        }

        return new MvcHtmlString(sb.ToString());
    }
}

GetMemberName是另一种扩展方法:

    public static string GetMemberName<TModel, T>(this Expression<Func<TModel, T>> input)
    {
        if (input == null)
            return null;

        if (input.Body.NodeType != ExpressionType.MemberAccess)
            return null;

        var memberExp = input.Body as MemberExpression;
        return memberExp != null ? memberExp.Member.Name : null;
    }

希望这有帮助。

答案 1 :(得分:13)

将ChangesOthersResult转换为数组并使用for循环输出如下内容:

for (int i = 0; i < Model.ChangesOthersResult.Length; i++ )    
{
   @Html.Hidden("ChangesOthersResult[" + i + "]", Model.ChangesOthersResult[i])
}

答案 2 :(得分:5)

扩展@GitteTitter的自定义对象列表解决方案:

@Html.HiddenForEnumerable(x => x.ValueTypes)    
@Html.HiddenForEnumerable(x => x.ViewModels, h=>h.Id, h=>h.Name)
@Html.HiddenForEnumerable(x => x.ViewModels, allPublicProps: true)

来源:

/// <summary>
/// Returns hiddens for every IEnumerable item, with it's selected properties, if any memberPropsExpression provided.
/// </summary>
public static MvcHtmlString HiddenForEnumerable<TModel, TModelProperty>(this HtmlHelper<TModel> helper,
    Expression<Func<TModel, IEnumerable<TModelProperty>>> expression, params Expression<Func<TModelProperty, object>>[] memberPropsExpressions)
{
    var sb = new StringBuilder();

    var membername = expression.GetMemberName();
    var model = helper.ViewData.Model;
    var list = expression.Compile()(model);

    var memPropsInfo = memberPropsExpressions.Select(x => new
    {
        MemberPropName = x.GetMemberName(),
        ListItemPropGetter = x.Compile()
    }).ToList();

    for (var i = 0; i < list.Count(); i++)
    {
        var listItem = list.ElementAt(i);
        if (memPropsInfo.Any())
        {
            foreach (var q in memPropsInfo)
            {
                sb.Append(helper.Hidden(string.Format("{0}[{1}].{2}", membername, i, q.MemberPropName), q.ListItemPropGetter(listItem)));
            }
        }
        else
        {
            sb.Append(helper.Hidden(string.Format("{0}[{1}]", membername, i), listItem));
        }
    }

    return new MvcHtmlString(sb.ToString());
}

/// <summary>
/// Returns hiddens for every IEnumerable item, with it's all public writable properties, if allPublicProps set to true.
/// </summary>
public static MvcHtmlString HiddenForEnumerable<TModel, TModelProperty>(this HtmlHelper<TModel> helper,
   Expression<Func<TModel, IEnumerable<TModelProperty>>> expression, bool allPublicProps)
{
    if (!allPublicProps)
        return HiddenForEnumerable(helper, expression);

    var sb = new StringBuilder();

    var membername = expression.GetMemberName();
    var model = helper.ViewData.Model;
    var list = expression.Compile()(model);

    var type = typeof(TModelProperty);
    var memPropsInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(x => x.GetSetMethod(false) != null && x.GetGetMethod(false) != null)
        .Select(x => new
        {
            MemberPropName = x.Name,
            ListItemPropGetter = (Func<TModelProperty, object>)(p => x.GetValue(p, null))
        }).ToList();

    if (memPropsInfo.Count == 0)
        return HiddenForEnumerable(helper, expression);

    for (var i = 0; i < list.Count(); i++)
    {
        var listItem = list.ElementAt(i);
        foreach (var q in memPropsInfo)
        {
            sb.Append(helper.Hidden(string.Format("{0}[{1}].{2}", membername, i, q.MemberPropName), q.ListItemPropGetter(listItem)));
        }
    }

    return new MvcHtmlString(sb.ToString());
}

public static string GetMemberName<TModel, T>(this Expression<Func<TModel, T>> input)
{
    if (input == null)
        return null;

    MemberExpression memberExp = null;

    if (input.Body.NodeType == ExpressionType.MemberAccess)
        memberExp = input.Body as MemberExpression;
    else if (input.Body.NodeType == ExpressionType.Convert)
        memberExp = ((UnaryExpression)input.Body).Operand as MemberExpression;

    return memberExp != null ? memberExp.Member.Name : null;
}

答案 3 :(得分:3)

不能使用.ForEach(),因为@ Html.HiddenFor(x =&gt; x.ChangesOthersResult)将创建相同的元素ID,模型在回发时将无法识别。

for (int i = 0; i < Model.ChangesOthersResult.Count(); i++ )    
{
    @Html.HiddenFor(x => x.ChangesOthersResult[I]);
}

答案 4 :(得分:3)

递归方法怎么样?

  <div ng-app="myApp" ng-controller="myCtrl">
        <select ng-model="selectedName" ng-options="x.names.name for x in names">
        </select>
  </div>

示例:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
       $scope.names = {
          "jobs": [
      {
        "Software": [
          {
            "name": "Developer",
            "displayName": "App Developer"
          },
          {
            "name": "Designer",
            "displayName": "App Designer"
          }
        ]
      },
      {
        "Business": [
          {
            "name": "Sales",
            "displayName": "Sales Manager"
          },
          {
            "name": "Marketing",
            "displayName": "Head of Marketing"
          }
        ]
      }
    ]
  };
  });

用法:

public static MvcHtmlString HiddenForEnumerable<TModel, TModelProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TModelProperty>>> expression, string prefix = null)
{
    var sb = new StringBuilder();

    var membername = expression.GetMemberName();
    var model = htmlHelper.ViewData.Model;
    var list = expression.Compile()(model);

    var type = typeof(TModelProperty);
    var memPropertyInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(x => x.GetSetMethod(false) != null && x.GetGetMethod(false) != null)
        .Select(x => new
        {
            Type = x.PropertyType,
            x.Name,
            Get = (Func<TModelProperty, object>)(p => x.GetValue(p, null))
        }).ToList();

    for (var i = 0; i < list.Count(); i++)
    {
        var listItem = list.ElementAt(i);
        if (memPropertyInfo.Any())
        {
            foreach (var m in memPropertyInfo)
            {
                var inputName = $"{prefix ?? ""}{membername}[{i}].{m.Name}";
                var inputValue = m.Get(listItem);
                var genericArguments = m.Type.GetGenericArguments();

                if (genericArguments.Any() && IsEnumerableType(m.Type))
                {
                    var delegateType = typeof(Func<,>).MakeGenericType(typeof(TModel), m.Type);
                    var bodyExpression = Expression.Constant(inputValue, m.Type);
                    var paramExpression = Expression.Parameter(typeof(TModel), "model");
                    var expressionTree = Expression.Lambda(delegateType, bodyExpression, new[] { paramExpression });
                    var hiddenForEnumerableInfo = typeof(HtmlHelpers).GetMethod("HiddenForEnumerable");
                    var hiddenForEnumerable = hiddenForEnumerableInfo.MakeGenericMethod(typeof(TModel), genericArguments[0]);
                    object[] args = { htmlHelper, expressionTree, inputName };

                    sb.Append(hiddenForEnumerable.Invoke(null, args));
                }
                else
                {
                    sb.Append(htmlHelper.Hidden(inputName, inputValue));
                }
            }
        }
        else
        {
            sb.Append(htmlHelper.Hidden($"{membername}[{i}]", listItem));
        }
    }

    return new MvcHtmlString(sb.ToString());
}

private static string GetMemberName<TModel, T>(this Expression<Func<TModel, T>> input)
{
    if (input == null)
        return null;

    MemberExpression memberExp = null;

    if (input.Body.NodeType == ExpressionType.MemberAccess)
        memberExp = input.Body as MemberExpression;
    else if (input.Body.NodeType == ExpressionType.Convert)
        memberExp = ((UnaryExpression)input.Body).Operand as MemberExpression;

    return memberExp?.Member.Name;
}

private static bool IsEnumerableType(Type type)
{
    return (type.GetInterface("IEnumerable") != null);
}

输出:

public class Model
{
    IEnumerable<Order> Orders { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public int ItemId { get; set; }
    public string Name { get; set; }
}

答案 5 :(得分:2)

在你的模型的构造函数中,新建了IEnumerable ChagesOthersResult

public Model ()
{
  ChangesOthersResult = new List<string>();
}

然后在视图中,使用for循环

for(int i = 0; i < Model.ChangesOthersResult.Count; i++)
{
  @Html.HiddenFor(x => x.ChangesOthersResult[i])
}

答案 6 :(得分:1)

与aspnetcore

相同
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace Proj.Helpers
{
    public static class HtmlHelpers
    {
        public static IHtmlContent HiddenForEnumerable<TModel, TModelProperty>(this IHtmlHelper<TModel> helper,
    Expression<Func<TModel, IEnumerable<TModelProperty>>> expression, params Expression<Func<TModelProperty, object>>[] memberPropsExpressions)
        {
            var hcb = new HtmlContentBuilder();

            var membername = expression.GetMemberName();
            var model = helper.ViewData.Model;
            var list = expression.Compile()(model);

            var memPropsInfo = memberPropsExpressions.Select(x => new
            {
                MemberPropName = x.GetMemberName(),
                ListItemPropGetter = x.Compile()
            }).ToList();

            for (var i = 0; i < list.Count(); i++)
            {
                var listItem = list.ElementAt(i);
                if (memPropsInfo.Any())
                {
                    foreach (var q in memPropsInfo)
                    {
                        hcb.AppendHtml(helper.Hidden(string.Format("{0}[{1}].{2}", membername, i, q.MemberPropName), q.ListItemPropGetter(listItem)));
                    }
                }
                else
                {
                    hcb.AppendHtml(helper.Hidden(string.Format("{0}[{1}]", membername, i), listItem));
                }
            }

            return hcb;
        }

        /// <summary>
        /// Returns hiddens for every IEnumerable item, with it's all public writable properties, if allPublicProps set to true.
        /// </summary>
        public static IHtmlContent HiddenForEnumerable<TModel, TModelProperty>(this IHtmlHelper<TModel> helper,
           Expression<Func<TModel, IEnumerable<TModelProperty>>> expression, bool allPublicProps)
        {
            if (!allPublicProps)
                return HiddenForEnumerable(helper, expression);

            var hcb = new HtmlContentBuilder();

            var membername = expression.GetMemberName();
            var model = helper.ViewData.Model;
            var list = expression.Compile()(model);

            var type = typeof(TModelProperty);
            var memPropsInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.GetSetMethod(false) != null && x.GetGetMethod(false) != null)
                .Select(x => new
                {
                    MemberPropName = x.Name,
                    ListItemPropGetter = (Func<TModelProperty, object>)(p => x.GetValue(p, null))
                }).ToList();

            if (memPropsInfo.Count == 0)
                return HiddenForEnumerable(helper, expression);

            for (var i = 0; i < list.Count(); i++)
            {
                var listItem = list.ElementAt(i);
                foreach (var q in memPropsInfo)
                {
                    hcb.AppendHtml(helper.Hidden(string.Format("{0}[{1}].{2}", membername, i, q.MemberPropName), q.ListItemPropGetter(listItem)));
                }
            }

            return hcb;
        }

        public static string GetMemberName<TModel, T>(this Expression<Func<TModel, T>> input)
        {
            if (input == null)
                return null;

            MemberExpression memberExp = null;

            if (input.Body.NodeType == ExpressionType.MemberAccess)
                memberExp = input.Body as MemberExpression;
            else if (input.Body.NodeType == ExpressionType.Convert)
                memberExp = ((UnaryExpression)input.Body).Operand as MemberExpression;

            return memberExp != null ? memberExp.Member.Name : null;
        }
    }
}